file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/56/0x9390695b8b1a754F3db4DB6eD74A9f017b9aB2b4/sources/project_/src/contracts/Paychanger.sol
Returns the total amount of vesting schedules. return the total amount of vesting schedules/
function getVestingSchedulesTotalAmount() public view returns(uint256){ return vestingSchedulesTotalAmount; }
3,229,658
pragma solidity >=0.4.22 <0.6.0; //pragma experimental ABIEncoderV2; //handles different roles on the Community Platform contract RoleManager { mapping (address => bool) verifiers; //have the right to verify users as Lessors or verified Renters mapping(address => bool) authorities; //have the right to vote in and out authorities, have their own tokens mapping(address => bool[5]) verifiedLessor; //verified Lessors can offer there property for rent on the platform -> obligations might differ whether you are allowed to lease out that specific object type mapping(address => bool[5]) verifiedRenter; //verified Renters have the right to rent specific property mapping(address => bool) blockedRenters; //users which are blocked from renting any objects (reasons might be steling of vehicles, or being an authority) mapping(address => bool) blockedLessors; //users which are blocked from leasing out any objects (reasons might be providing fake trips or denying end of trip with no basis) vote proposal; //Voting proposal, only one at one time, vote is a struct // address lastProposer; //Authorities can not propose more than one time in a row to prevent spamming. -> add block.number addition mapping(address => uint256) lastProposed; //block number of when this authority did propose last time, authorities can only propose every >10 blocks (-> 50 secs) to prevent spamming uint256 authorityCounter; //How many autohrities are in the network? //Modifiers are used to manage function access among roles modifier onlyVerifiers() { require (verifiers[msg.sender] == true); _; } modifier onlyAuthorities() { require (authorities[msg.sender] == true); _; } struct vote { address proposedAuthority; uint256 PositiveVotesReceived; uint256 NegativeVotesRecived; mapping (address => bool) hasVoted; //has the authority at that address already voted? string description; //a description of the votedAddress } constructor(address firstAddress) public { authorities[firstAddress] = true; //first adress is announced as first authority on the platform verifiers[firstAddress] = true; blockedRenters[firstAddress] = true; //authorities need to be blocked from rentals, see explanation in evaluateVotes() functions // authorityTokens[msg.sender] = new CommunityToken(100, msg.sender, description, description); //generates new CommunityToken for that authority } //Used for adding and dropping authorities function proposeAuthority(address proposedAddress, string memory description) public onlyAuthorities { address defAddress; //change to address(0) if(proposal.proposedAuthority == defAddress && block.number > lastProposed[msg.sender]+10) //only possible if last Vote is already over and Proposer has not proposed within the last 10 blocks (prevents spamming) { vote memory temp; //can be deleted prob. and manually assign PositiveVotesReceived, .. to 0 proposal = temp; proposal.proposedAuthority = proposedAddress; proposal.description = description; lastProposed[msg.sender] = block.number; } } //Voting and Evaluation, at exactly 50% Voting is in Favor of authority function voteAuthority(bool voteDecision) public onlyAuthorities { require(proposal.hasVoted[msg.sender] == false); if(voteDecision == true) { proposal.PositiveVotesReceived++; } else { proposal.NegativeVotesRecived++; } evaluateVotes(); } //Evaluation, at exactly 50% Voting is in Favor of authority function evaluateVotes() public //maybe change to internal { if(proposal.PositiveVotesReceived*2 >= authorityCounter) //Vote is over, authority gets added (or stays if it was already an autohrity) { if(authorities[proposal.proposedAuthority] == false) { authorities[proposal.proposedAuthority] = true; authorityCounter++; blockedRenters[proposal.proposedAuthority] = true; //authorities must be blcoked renters as during trip start all payments get blocked by the token manager, an authority which would get blocked in this context could no withdrawl tokens for users at the same time, also full debt based payment with own tokens should not be permitted // authorityTokens[proposal.proposedAuthority] = new CommunityToken(100, proposal.proposedAuthority, proposal.description, proposal.description); //generates new CommunityToken for that authority // tokens[numberOfTokens] = new CommunityToken(100, proposal.proposedAuthority, proposal.description, proposal.description); //generates new CommunityToken for that authority } vote memory newvote; proposal = newvote; } if(proposal.NegativeVotesRecived*2 > authorityCounter) //Vote is over, authority gets removed (or cant join if it wasnt already an autohrity) { if(authorities[proposal.proposedAuthority] == true) { authorities[proposal.proposedAuthority] = false; authorityCounter--; //*********Needs to pay back all leftover tokens************* //the former authority cannot be unblocked from not being allowed to rent since leftover tokens may still exist and have to be exchanged in fiat at any time a user demands } vote memory newvote; proposal = newvote; } } //Every authority has the right to step back, as total number of authories changes, current vote has to be reavluated function removeSelfFromAuthority() public onlyAuthorities { authorities[msg.sender] = false; if(msg.sender == proposal.proposedAuthority) //need to check if authority is currently in vote to not destroy the system { vote memory newvote; proposal = newvote; } authorityCounter--; evaluateVotes(); //Voting may have changed, need to reavluate } //Verifiers can verify Lessors function verifiyCarLessor(address userAddress, uint8 objectType) public onlyVerifiers() { verifiedLessor[userAddress] [objectType] = true; } //Verifiers can verify Renters function verifyRenter(address userAddress, uint8 objectType) public onlyVerifiers() { verifiedRenter[userAddress][objectType] = true; } //Authoirites can add Verifiers function addVerifier(address a) public onlyAuthorities { verifiers[a] = true; } //Authoirites can remove Verifiers if these are not other Authorities function removeVerifier(address a) public onlyAuthorities { require(a == msg.sender || authorities[a] == false); //authorities can only remove a verifier if the verifier is not another authority (unless they want to remove themselves) verifiers[a] = false; } //blocks user from renting or leasing out sharing objects, blockedType = false -> renting, blockedType = true -> sharing //A String message could be used and emmited or stored to justify the block function blockUser(address a, bool blockedType) public onlyAuthorities { require(authorities[a] == false); //authorities cannot block other authorities if(blockedType == false) blockedRenters[a] = true; else blockedLessors[a] = true; } //unblocks user from renting or leasing out sharing objects, blockedType = 0 -> renting, blockedType = 1 -> sharing function unblockUser(address a, bool blockedType) public onlyAuthorities { require(authorities[a] == false); //authorities must be blocked for renting and should not be blocked for leasing, this remains cosntant and they should not be able to unblock other authorities (or themselves) if(blockedType == false) blockedRenters[a] = false; else blockedLessors[a] = false; } //function to be removed later, convinient for testing to quickly verify oneself for leasing out and renting all objects function testVerifyme(address a) public { verifiedRenter[a][0] = true; verifiedRenter[a][1] = true; verifiedRenter[a][2] = true; verifiedRenter[a][3] = true; verifiedRenter[a][4] = true; verifiedLessor[a][0] = true; verifiedLessor[a][1] = true; verifiedLessor[a][2] = true; verifiedLessor[a][3] = true; verifiedLessor[a][4] = true; } //getter Section function isAuthority(address a) public view returns(bool) { return authorities[a]; } function isVerifier(address a) public view returns(bool) { return verifiers[a]; } function isVerifiedLessor(address a, uint8 index) public view returns(bool) { return verifiedLessor[a][index]; } function isVerifiedRenter(address a, uint8 index) public view returns(bool) { return verifiedRenter[a][index]; } function isBlocked(address a, bool blockedType) public view returns(bool) { if(blockedType == false) return blockedRenters[a]; else return blockedLessors[a]; } }
Voting and Evaluation, at exactly 50% Voting is in Favor of authority
function voteAuthority(bool voteDecision) public onlyAuthorities { require(proposal.hasVoted[msg.sender] == false); if(voteDecision == true) { proposal.PositiveVotesReceived++; } else { proposal.NegativeVotesRecived++; } evaluateVotes(); }
12,902,589
./full_match/1/0x1b86B82a6cbfb585DE746984026eB993aB4E9013/sources/contracts/Interfaces/external/IUniswapV3SwapRouter.sol
Router token swapping functionality Functions for swapping tokens via Uniswap V3
interface IUniswapV3SwapRouter { pragma solidity 0.8.4; struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } }
2,960,297
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "../Common/Context.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "./Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Oracle/ChainlinkETHUSDPriceConsumer.sol"; import "../Governance/AccessControl.sol"; contract FRAXStablecoin is ERC20Custom, AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { FRAX, FXS } PriceChoice price_choices; ChainlinkETHUSDPriceConsumer eth_usd_pricer; uint8 eth_usd_pricer_decimals; UniswapPairOracle fraxEthOracle; UniswapPairOracle fxsEthOracle; string public symbol; uint8 public decimals = 18; address[] public owners; address governance_address; address public creator_address; address public timelock_address; address public fxs_address; address public frax_eth_oracle_address; address public fxs_eth_oracle_address; address public weth_address; address public eth_usd_consumer_address; uint256 public genesis_supply = 1000000e18; // 1M. This is to help with establishing the Uniswap pools, as they need liquidity mapping(PriceChoice => address[]) private stablecoin_oracles; // // The addresses in this array are added by the oracle and these contracts are able to mint frax address[] frax_pools_array; // Mapping is also used for faster verification mapping(address => bool) public frax_pools; uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102 uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER"); bool public collateral_ratio_paused = false; /* ========== MODIFIERS ========== */ modifier onlyCollateralRatioPauser() { require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender)); _; } modifier onlyPools() { require(frax_pools[msg.sender] == true, "Only frax pools can mint new FRAX"); _; } modifier onlyByGovernance() { require(msg.sender == governance_address, "You're not the governance contract :p"); _; } modifier onlyByOwnerOrGovernance() { // Loop through the owners until one is found bool found = false; for (uint i = 0; i < owners.length; i++){ if (owners[i] == msg.sender) { found = true; break; } } require(found, "You're not an owner"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _symbol, address _creator_address, address _timelock_address ) public { symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); owners.push(creator_address); owners.push(timelock_address); _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); } /* ========== VIEWS ========== */ // Choice = 'FRAX' or 'FXS' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the ETH / USD price first, and cut it down to 1e6 precision uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(1e6).div(uint256(10) ** eth_usd_pricer_decimals); uint256 price_vs_eth; if (choice == PriceChoice.FRAX) { price_vs_eth = uint256(fraxEthOracle.consult(weth_address, 1e6)); } else if (choice == PriceChoice.FXS) { price_vs_eth = uint256(fxsEthOracle.consult(weth_address, 1e6)); } else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)"); // Will be in 1e6 format return price_vs_eth.mul(1e6).div(eth_usd_price); } // Returns X FRAX = 1 USD function frax_price() public view returns (uint256) { return oracle_price(PriceChoice.FRAX); } // Returns X FXS = 1 USD function fxs_price() public view returns (uint256) { return oracle_price(PriceChoice.FXS); } // This is needed to avoid costly repeat calls to different getter functions // It is cheaper gas-wise to just dump everything and only use some of the info function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.FRAX), // frax_price() oracle_price(PriceChoice.FXS), // fxs_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee // redemption_fee() ); } // Iterate through all frax pools and calculate all value of collateral in all pools globally function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 += FraxPool(frax_pools_array[i]).collatDollarBalance(); } } return total_collateral_value_d18; } /* ========== PUBLIC FUNCTIONS ========== */ // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion. uint256 last_call_time; // Last time the refreshCollateralRatio function was called function refreshCollateralRatio() public { require(collateral_ratio_paused == false, "Collateral Ratio has been paused"); require(block.timestamp - last_call_time >= 3600 && frax_price() != 1000000); // 3600 seconds means can be called once per hour, 86400 seconds is per day, callable only if FRAX price is not $1 uint256 tot_collat_value = globalCollateralValue(); // If tot_collat_value > totalSupply(), this will truncate to 0 and underflow below. // Need to multiply by 1e6 to avoid this issue and divide by 1e6 later when used in other places // uint256 globalC_ratio = (totalSupply().mul(1e6)).div(tot_collat_value); uint256 globalC_ratio; if (tot_collat_value == 0) globalC_ratio = 0; else { globalC_ratio = (tot_collat_value.mul(1e6)).div(totalSupply()); // Step increments are .5% if (frax_price() > 1000000) { global_collateral_ratio = globalC_ratio.sub(5000); } else { global_collateral_ratio = globalC_ratio.add(5000); } } last_call_time = block.timestamp; // Set the time of the last expansion } /* ========== RESTRICTED FUNCTIONS ========== */ // Public implementation of internal _mint() function mint(uint256 amount) public virtual onlyByOwnerOrGovernance { _mint(msg.sender, amount); } // Used by pools when user redeems function pool_burn_from(address b_address, uint256 b_amount) public onlyPools { super._burnFrom(b_address, b_amount); emit FRAXBurned(b_address, msg.sender, b_amount); } // This function is what other frax pools will call to mint new FRAX function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerOrGovernance { frax_pools[pool_address] = true; frax_pools_array.push(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerOrGovernance { // Delete from the mapping delete frax_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } // Adds a new stablecoin oracle function addStablecoinOracle(PriceChoice choice, address oracle_address) public onlyByOwnerOrGovernance { stablecoin_oracles[choice].push(oracle_address); } // Removes an oracle function removeStablecoinOracle(PriceChoice choice, address oracle_address) public onlyByOwnerOrGovernance { // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < stablecoin_oracles[choice].length; i++){ if (stablecoin_oracles[choice][i] == oracle_address) { stablecoin_oracles[choice][i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } // Adds an owner function addOwner(address owner_address) public onlyByOwnerOrGovernance { owners.push(owner_address); } // Removes an owner function removeOwner(address owner_address) public onlyByOwnerOrGovernance { // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < owners.length; i++){ if (owners[i] == owner_address) { owners[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance { redemption_fee = red_fee; } function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance { minting_fee = min_fee; } function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance { fxs_address = _fxs_address; } function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance { eth_usd_consumer_address = _eth_usd_consumer_address; eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address); eth_usd_pricer_decimals = eth_usd_pricer.getDecimals(); } // Sets the FRAX_ETH Uniswap oracle address function setFRAXEthOracle(address _frax_addr, address _weth_address) public onlyByOwnerOrGovernance { frax_eth_oracle_address = _frax_addr; fraxEthOracle = UniswapPairOracle(_frax_addr); weth_address = _weth_address; } // Sets the FXS_ETH Uniswap oracle address function setFXSEthOracle(address _fxs_addr, address _weth_address) public onlyByOwnerOrGovernance { fxs_eth_oracle_address = _fxs_addr; fxsEthOracle = UniswapPairOracle(_fxs_addr); weth_address = _weth_address; } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; } /* ========== EVENTS ========== */ // Track FXS burned event FRAXBurned(address indexed from, address indexed to, uint256 amount); }
Removes an owner 'Delete' from the array by setting the address to 0x0
function removeOwner(address owner_address) public onlyByOwnerOrGovernance { for (uint i = 0; i < owners.length; i++){ if (owners[i] == owner_address) { break; } } }
15,836,530
./partial_match/1/0xfc4913214444aF5c715cc9F7b52655e788A569ed/sources/Icosa.sol
Updates all stake values which must wait for the follwing day to be properly accounted for. Primarily keeps track of payout per point and stake points per day./ Most of the magic happens in this function HDRN Staking if there are stakes in the pool, else carry the previous day forward. calculate next day's payout per point drain the collection carry the would be payout forward until there are stakes in the pool if there are stakes in the pool, else carry the previous day forward. calculate next day's ICSA payout per point calculate next day's HDRN payout per point drain the collections carry the would be payout forward until there are stakes in the pool if there are stakes in the pool, else carry the previous day forward. calculate next day's payout per point drain the collection carry the would be payout forward until there are stakes in the pool
function _stakeDailyUpdate () internal { uint256 hdrnDay = _hdrn.currentDay(); if (currentDay < hdrnDay) { uint256 daysPast = hdrnDay - currentDay; for (uint256 i = 0; i < daysPast; i++) { HEXGlobals memory hx = _hexGlobalsLoad(); HDRNDailyData memory hdrn = _hdrnDailyDataLoad(currentDay); uint256 newPoolPoints; uint256 newHdrnPoolPayout; newPoolPoints = (hdrnPoolPoints[currentDay + 1] + hdrnPoolPoints[currentDay]) - hdrnPoolPointsRemoved; if (newPoolPoints > 0) { newHdrnPoolPayout = ((hdrn.dayBurntTotal * _decimalResolution) / hx.shareRate) + (hdrnPoolIcsaCollected * _decimalResolution) + (icsaSeedLiquidity[currentDay + 1] * _decimalResolution); newHdrnPoolPayout /= newPoolPoints; newHdrnPoolPayout += hdrnPoolPayout[currentDay]; hdrnPoolIcsaCollected = 0; newHdrnPoolPayout = hdrnPoolPayout[currentDay]; hdrnPoolIcsaCollected += (hdrn.dayBurntTotal / hx.shareRate) + icsaSeedLiquidity[currentDay + 1]; } hdrnPoolPayout[currentDay + 1] = newHdrnPoolPayout; hdrnPoolPoints[currentDay + 1] = newPoolPoints; emit HDRNStakingStats ( uint256(uint48 (block.timestamp)) | (uint256(uint104(newPoolPoints)) << 48) | (uint256(uint104(hdrnPoolPointsRemoved)) << 152), newHdrnPoolPayout, currentDay + 1 ); hdrnPoolPointsRemoved = 0; uint256 newIcsaPoolPayoutHdrn; newPoolPoints = (icsaPoolPoints[currentDay + 1] + icsaPoolPoints[currentDay]) - icsaPoolPointsRemoved; if (newPoolPoints > 0) { newIcsaPoolPayoutIcsa = ((hdrn.dayBurntTotal * _decimalResolution) / hx.shareRate) + (icsaPoolIcsaCollected * _decimalResolution) + (icsaSeedLiquidity[currentDay + 1] * _decimalResolution); newIcsaPoolPayoutIcsa /= newPoolPoints; newIcsaPoolPayoutIcsa += icsaPoolPayoutIcsa[currentDay]; newIcsaPoolPayoutHdrn = (icsaPoolHdrnCollected * _decimalResolution) + (hdrnSeedLiquidity[currentDay + 1] * _decimalResolution); newIcsaPoolPayoutHdrn /= newPoolPoints; newIcsaPoolPayoutHdrn += icsaPoolPayoutHdrn[currentDay]; icsaPoolIcsaCollected = 0; icsaPoolHdrnCollected = 0; newIcsaPoolPayoutIcsa = icsaPoolPayoutIcsa[currentDay]; newIcsaPoolPayoutHdrn = icsaPoolPayoutHdrn[currentDay]; icsaPoolIcsaCollected += (hdrn.dayBurntTotal / hx.shareRate) + icsaSeedLiquidity[currentDay + 1]; icsaPoolHdrnCollected += hdrnSeedLiquidity[currentDay + 1]; } icsaPoolPayoutIcsa[currentDay + 1] = newIcsaPoolPayoutIcsa; icsaPoolPayoutHdrn[currentDay + 1] = newIcsaPoolPayoutHdrn; icsaPoolPoints[currentDay + 1] = newPoolPoints; emit ICSAStakingStats ( uint256(uint48 (block.timestamp)) | (uint256(uint104(newPoolPoints)) << 48) | (uint256(uint104(icsaPoolPointsRemoved)) << 152), newIcsaPoolPayoutIcsa, newIcsaPoolPayoutHdrn, currentDay + 1 ); icsaPoolPointsRemoved = 0; newPoolPoints = (nftPoolPoints[currentDay + 1] + nftPoolPoints[currentDay]) - nftPoolPointsRemoved; if (newPoolPoints > 0) { newNftPoolPayout = ((hdrn.dayBurntTotal * _decimalResolution) / hx.shareRate) + (nftPoolIcsaCollected * _decimalResolution) + (icsaSeedLiquidity[currentDay + 1] * _decimalResolution); newNftPoolPayout /= newPoolPoints; newNftPoolPayout += nftPoolPayout[currentDay]; nftPoolIcsaCollected = 0; newNftPoolPayout = nftPoolPayout[currentDay]; nftPoolIcsaCollected += (hdrn.dayBurntTotal / hx.shareRate) + icsaSeedLiquidity[currentDay + 1]; } nftPoolPayout[currentDay + 1] = newNftPoolPayout; nftPoolPoints[currentDay + 1] = newPoolPoints; emit NFTStakingStats ( uint256(uint48 (block.timestamp)) | (uint256(uint104(newPoolPoints)) << 48) | (uint256(uint104(nftPoolPointsRemoved)) << 152), newNftPoolPayout, currentDay + 1 ); nftPoolPointsRemoved = 0; } } }
15,721,927
pragma solidity ^0.4.18; /** * @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; } } pragma solidity ^0.4.18; /** * @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; } } // <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 pragma solidity ^0.4.18; 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&#39;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&#39;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)); // Convert from seconds to ledger timer ticks _delay *= 10; 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 memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, 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 &#39;LP\x01&#39; (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 &#39;LP\x01&#39; (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; require(prefix.length == n_random_bytes); 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 &#39;result&#39; 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&#39;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&#39;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&#39;t update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can&#39;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 // &#39;mload&#39; will pad with zeroes if we overread. // There is no &#39;mload8&#39; to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // &#39;byte&#39; is not working due to the Solidity parser, so lets // use the second best option, &#39;and&#39; // 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> pragma solidity ^0.4.19; /// @title EtherHiLo /// @dev the contract than handles the EtherHiLo app contract EtherHiLo is usingOraclize, Ownable { uint8 constant NUM_DICE_SIDES = 13; // settings uint public rngCallbackGas; uint public minBet; uint public maxBetThresholdPct; bool public gameRunning; // state uint public balanceInPlay; Game[] public gamesCompleted; mapping(address => Game[]) public playerGamesCompleted; mapping(address => Game) private gamesInProgress; mapping(bytes32 => address) private rollIdToGameAddress; event GameStarted(address indexed player, uint indexed playerGameNumber, uint bet); event FirstRoll(address indexed player, uint indexed playerGameNumber, uint bet, uint roll); event DirectionChosen(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, BetDirection direction); event GameFinished(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, uint finalRoll, uint winnings, uint payout); enum BetDirection { None, Low, High } // the game object struct Game { address player; uint bet; uint firstRoll; uint finalRoll; BetDirection direction; uint winnings; uint when; } // modifier that requires the game is running modifier gameIsRunning() { require(gameRunning); _; } // modifier that requires there is a game in progress // for the player modifier gameInProgress(address player) { require(player != address(0)); require(gamesInProgress[player].player != address(0)); _; } // modifier that requires there is not a game in progress // for the player modifier gameNotInProgress(address player) { require(player != address(0)); require(gamesInProgress[player].player == address(0)); _; } // modifier that requires the caller come from oraclize modifier onlyOraclize { require(msg.sender == oraclize_cbAddress()); _; } // modifier that insists on a valid bet modifier validBet(uint bet) { require(isValidBet(bet)); _; } // the constructor function EtherHiLo() public { oraclize_setProof(proofType_Ledger); setRNGCallbackGas(4500000); setMinBet(1 finney); setGameRunning(true); setMaxBetThresholdPct(50); } /// Default function function() external payable { } /// ======================= /// EXTERNAL GAME RELATED FUNCTIONS function isGameRunning() public view returns (bool) { return gameRunning; } // begins a game function beginGame() public payable gameIsRunning gameNotInProgress(msg.sender) validBet(msg.value) { address player = msg.sender; uint bet = msg.value; Game memory game = Game({ player: player, bet: bet, firstRoll: 0, finalRoll: 0, direction: BetDirection.None, winnings: 0, when: block.timestamp }); balanceInPlay = balanceInPlay + game.bet; gamesInProgress[player] = game; rollDie(player); GameStarted(player, playerGamesCompleted[player].length, bet); } // finishes a game that is in progress function finishGame(BetDirection direction) public gameInProgress(msg.sender) { address player = msg.sender; require(player != address(0)); require(direction != BetDirection.None); Game storage game = gamesInProgress[player]; require(game.player != address(0)); game.direction = direction; gamesInProgress[player] = game; rollDie(player); DirectionChosen(player, playerGamesCompleted[player].length, game.bet, game.firstRoll, direction); } // determins whether or not the caller is in a game function getGameState(address player) public view returns (bool, uint, uint, uint, BetDirection, uint, uint, uint) { require(player != address(0)); return ( gamesInProgress[player].player != address(0), gamesInProgress[player].bet, gamesInProgress[player].firstRoll, gamesInProgress[player].finalRoll, gamesInProgress[player].direction, playerGamesCompleted[player].length, getMinBet(), getMaxBet() ); } // Indicates whether or not the given bet is a valid bet function isValidBet(uint bet) public view returns (bool) { return bet >= minBet && bet <= getMaxBet(); } // Returns the minimum bet function getMinBet() public view returns (uint) { return minBet; } // Returns the maximum bet function getMaxBet() public view returns (uint) { return SafeMath.div(SafeMath.div(SafeMath.mul(this.balance - balanceInPlay, maxBetThresholdPct), 100), 12); } // Returns the balance in play function getBalanceInPlay() public view returns (uint) { return balanceInPlay; } // Returns the number of games completed function getNumberOfGamesCompleted() public view returns (uint) { return gamesCompleted.length; } // Returns the game completed at the given index function getGameCompleted(uint index) public view returns (address, uint, uint, uint, BetDirection, uint, uint) { Game storage game = gamesCompleted[index]; return (game.player, game.bet, game.firstRoll, game.finalRoll, game.direction, game.winnings, game.when); } // Returns the number of games a player completed function getNumberOfMyGamesCompleted(address player) public view returns (uint) { require(player != address(0)); return playerGamesCompleted[player].length; } // Returns the game a player completed at the given index function getMyGameCompleted(address player, uint index) public view returns (address, uint, uint, uint, BetDirection, uint, uint) { require(player != address(0)); Game storage game = playerGamesCompleted[player][index]; return (game.player, game.bet, game.firstRoll, game.finalRoll, game.direction, game.winnings, game.when); } // calculates winnings for the given bet and percent function calculateWinnings(uint bet, uint percent) public pure returns (uint) { return SafeMath.div(SafeMath.mul(bet, percent), 100); } // Returns the win percent when going low on the given number function getLowWinPercent(uint number) public pure returns (uint) { require(number >= 2 && number <= NUM_DICE_SIDES); if (number == 2) { return 1200; } else if (number == 3) { return 500; } else if (number == 4) { return 300; } else if (number == 5) { return 300; } else if (number == 6) { return 200; } else if (number == 7) { return 180; } else if (number == 8) { return 150; } else if (number == 9) { return 140; } else if (number == 10) { return 130; } else if (number == 11) { return 120; } else if (number == 12) { return 110; } else if (number == 13) { return 100; } } // Returns the win percent when going high on the given number function getHighWinPercent(uint number) public pure returns (uint) { require(number >= 1 && number < NUM_DICE_SIDES); if (number == 1) { return 100; } else if (number == 2) { return 110; } else if (number == 3) { return 120; } else if (number == 4) { return 130; } else if (number == 5) { return 140; } else if (number == 6) { return 150; } else if (number == 7) { return 180; } else if (number == 8) { return 200; } else if (number == 9) { return 300; } else if (number == 10) { return 300; } else if (number == 11) { return 500; } else if (number == 12) { return 1200; } } /// ======================= /// INTERNAL GAME RELATED FUNCTIONS // process a successful roll function processDiceRoll(address player, uint roll) private { Game storage game = gamesInProgress[player]; require(game.player != address(0)); if (game.firstRoll == 0) { game.firstRoll = roll; gamesInProgress[player] = game; FirstRoll(player, playerGamesCompleted[player].length, game.bet, game.firstRoll); } else if (game.finalRoll == 0) { game.finalRoll = roll; uint winnings = 0; if (game.direction == BetDirection.High && game.finalRoll > game.firstRoll) { winnings = calculateWinnings(game.bet, getHighWinPercent(game.firstRoll)); } else if (game.direction == BetDirection.Low && game.finalRoll < game.firstRoll) { winnings = calculateWinnings(game.bet, getLowWinPercent(game.firstRoll)); } game.winnings = winnings; // this should never happen according to the odds, // and the fact that we don&#39;t allow people to bet // so large that they can take the whole pot in one // fell swoop - however, a number of people could // theoretically all win simultaneously and cause // this scenario. This will try to at a minimum // send them back what they bet and then since it // is recorded on the blockchain we can verify that // the winnings sent don&#39;t match what they should be // and we can manually send the rest to the player. uint transferAmount = winnings; if (transferAmount > this.balance) { if (game.bet < this.balance) { transferAmount = game.bet; } else { transferAmount = SafeMath.div(SafeMath.mul(this.balance, 90), 100); } } balanceInPlay = balanceInPlay - game.bet; gamesCompleted.push(game); playerGamesCompleted[player].push(game); if (transferAmount > 0) { game.player.transfer(transferAmount); } GameFinished(player, playerGamesCompleted[player].length - 1, game.bet, game.firstRoll, game.finalRoll, game.winnings, transferAmount); delete gamesInProgress[player]; } } // process a failed roll function processFailedVerification(bytes32 rollId) private { address player = rollIdToGameAddress[rollId]; require(player != address(0)); Game storage game = gamesInProgress[player]; require(game.player != address(0)); game.player.transfer(game.bet); delete rollIdToGameAddress[rollId]; delete gamesInProgress[player]; } // roll the dice for a player function rollDie(address player) private { uint N = 7; uint delay = 0; bytes32 queryId = oraclize_newRandomDSQuery(delay, N, rngCallbackGas); rollIdToGameAddress[queryId] = player; } /// ======================= /// ORACLIZE RELATED FUNCTIONS // the callback function is called by Oraclize when the result is ready // the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code: // the proof validity is fully verified on-chain function __callback(bytes32 _queryId, string _result, bytes _proof) onlyOraclize { if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) { processFailedVerification(_queryId); } else { address player = rollIdToGameAddress[_queryId]; require(player != address(0)); uint randomNumber = (uint(keccak256(_result)) % NUM_DICE_SIDES) + 1; processDiceRoll(player, randomNumber); delete rollIdToGameAddress[_queryId]; } } /// OWNER / MANAGEMENT RELATED FUNCTIONS // fail safe for balance transfer function transferBalance(address to, uint amount) public onlyOwner { to.transfer(amount); } // cleans up a player abandoned game, but only if it&#39;s // greater than 24 hours old. function cleanupAbandonedGame(address player) public onlyOwner { require(player != address(0)); Game storage game = gamesInProgress[player]; require(game.player != address(0)); uint elapsed = block.timestamp - game.when; require(elapsed >= 86400); game.player.transfer(game.bet); delete gamesInProgress[game.player]; } // set RNG callback gas function setRNGCallbackGas(uint gas) public onlyOwner { rngCallbackGas = gas; } // set the minimum bet function setMinBet(uint bet) public onlyOwner { minBet = bet; } // set whether or not the game is running function setGameRunning(bool v) public onlyOwner { gameRunning = v; } // set the max bet threshold percent function setMaxBetThresholdPct(uint v) public onlyOwner { maxBetThresholdPct = v; } // Transfers the current balance to the owner and terminates the contract. function destroy() public onlyOwner { selfdestruct(owner); } // Transfers the current balance to the recepient and terminates the contract. function destroyAndSend(address _recipient) public onlyOwner { selfdestruct(_recipient); } }
the callback function is called by Oraclize when the result is ready the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code: the proof validity is fully verified on-chain
function __callback(bytes32 _queryId, string _result, bytes _proof) onlyOraclize { if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) { processFailedVerification(_queryId); address player = rollIdToGameAddress[_queryId]; require(player != address(0)); uint randomNumber = (uint(keccak256(_result)) % NUM_DICE_SIDES) + 1; processDiceRoll(player, randomNumber); delete rollIdToGameAddress[_queryId]; } }
8,000,417
/// @title 墨客联盟链BAAS ERC721合约 /// @author 野驴阿保机 /// @notice 这个合约是对标准ERC721合约的扩展 pragma solidity ^0.5.0; import "OpenZeppelin/token/ERC721Full.sol"; import "OpenZeppelin/token//ERC721Holder.sol"; contract BaasBlock is ERC721Full, ERC721Holder { // 这是每一个721token的固定属性,铸造的时候设定 mapping(uint256 => string) public property; function() external payable {} constructor () ERC721Full("Baas 721 Token", "B7T") public { } event tokenMinted(uint256 indexed tokenId, string property, string tokenUri); event memoAdded(uint256 indexed tokenId, string memo); event transactionMemo(uint256 indexed tokenId, string memo); /// @notice 设置一个token的属性 /// @param _tokenId 唯一的通证id /// @param _property 属性是一串字符串,从一个结构转化而来。 function setProperty(uint256 _tokenId, string memory _property) public { address owner = ownerOf(_tokenId); require(msg.sender == owner, "only contract owner"); property[_tokenId] = _property; } /// @notice 读取一个token的属性 /// @param _tokenId 唯一的通证id function getProperty(uint256 _tokenId) public view returns (string memory) { return property[_tokenId]; } /// @notice 为给定的token添加一条memo /// @param _tokenId 唯一的通证id /// @param _memo 记录一些附加的信息 function addMemo(uint256 _tokenId, string memory _memo) public { // 不做检查,如果是空的字符串,就空的字符串 // require(bytes(_memo).length > 0, "should not be empty memo") emit memoAdded(_tokenId, _memo); } function transferWithMemo(address _from, address _to, uint256 _tokenId, string memory _memo) public { transferFrom(_from, _to, _tokenId); if (bytes(_memo).length > 0) { emit transactionMemo(_tokenId, _memo); } } function mint(uint256 _tokenId, string memory _property, string memory _tokenUri) public { _mint(msg.sender, _tokenId); // 这里不对property做判断 - mint的时候,如果不需要property, 则使用"", // 这样这个token总是有个property. 因此getProperty不会出错。 property[_tokenId] = _property; // 这里设置token的metadata, 这里也不使用baseUrl _setTokenURI(_tokenId, _tokenUri); emit tokenMinted(_tokenId, _property, _tokenUri); } }
这里不对property做判断 - mint的时候,如果不需要property, 则使用"", 这样这个token总是有个property. 因此getProperty不会出错。 这里设置token的metadata, 这里也不使用baseUrl
function mint(uint256 _tokenId, string memory _property, string memory _tokenUri) public { _mint(msg.sender, _tokenId); property[_tokenId] = _property; _setTokenURI(_tokenId, _tokenUri); emit tokenMinted(_tokenId, _property, _tokenUri); }
973,400
pragma solidity ^0.4.8; contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract EOUNCE{ /* Public variables of the token */ string public standard = 'E-OUNCE 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances . */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function EOUNCE() { balanceOf[msg.sender] = 750000000 * 1000000000000000000; // Give the creator all initial tokens totalSupply = 750000000 * 1000000000000000000; // Update total supply name = "E-OUNCE"; // Set the name for display purposes symbol = "EAS"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes } /* Send coins */ function transfer(address _to, uint256 _value) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) returns (bool success) { if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(_from, _value); return true; } }
Public variables of the token / This creates an array with all balances . / This generates a public event on the blockchain that will notify clients / This notifies clients about the amount burnt / Initializes contract with initial supply tokens to the creator of the contract /
function EOUNCE() { }
14,828,728
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * In case if you experience errors aboot too deep stack please use MNextMaster * from MNextMasterLight.sol. * * It performs less checks which means less security on one hand but * compatibility with common configured EVMs like this of Ethereum ecosystem * on the other hand. * * To see the differences please read the leading comment in the file * MNextMasterLight.sol. */ import './MNextDataModel.sol'; contract MNextMaster is MNextDataModel{ /* * ########### * # STRUCTS # * ########### */ // //////// // / BANK / // //////// struct BankWrapper { Bank bank; bool isLocked; } // ///////// // / CHECK / // ///////// struct CheckWrapper { Check check; bool isLocked; } // //////// // / USER / // //////// struct User { uint8 state; bool isLocked; } // ////////////// // / UTXO (BTC) / // ////////////// struct BTCutxo { address utxo; uint256 satoshi; uint16 bank; uint256 account; } /* * #################### * # PUBLIC VARIABLES # * #################### */ ////////////////////////////// // SYSTEM'S KEY DESCRIPTORS // ////////////////////////////// string public name; string public token; string public symbol; string public admin; string public api; string public site; string public explorer; mapping (uint8 => NoteType) public noteTypes; /* * ##################### * # PRIVATE VARIABLES # * ##################### */ ///////////////////////////// // SYSTEM'S KEY CONTAINERS // ///////////////////////////// mapping (uint16 => BankWrapper) private _banks; mapping (uint256 => CheckWrapper) private _checks; mapping (uint256 => Coin) private _coins; mapping (uint256 => Note) private _notes; mapping (address => User) private _users; mapping (uint256 => BTCutxo) private _utxos; ///////////////////////////// // SYSTEM'S KEY CONDITIONS // ///////////////////////////// uint256 private _satoshiBase; int32 private _reserveRatio; uint16 private _multiplier; ///////////////////////// // MAINTENANCE HELPERS // ///////////////////////// uint16 private _nextBankId; uint256 private _nextCoinId; uint256 private _nextNoteId; uint256 private _nextCheckId; uint256 private _utxoPointer; //////////////////////////////// // SYSTEM ADMIN'S CREDENTIALS // //////////////////////////////// address payable private _rootUser; bytes32 private _rootKey; /* * Contract constructor * -------------------- * Construct the contract * * @param string memory sentence * A sentence to protect master access. * @param uint256 satoshiBase_ * Value to set as system's base unit. * @param int32 reserveRatio_ * Value to set as system's reserve ratio. * @param uint16 multiplier_ * Value to set as system's multiplier. */ constructor(string memory sentence, uint256 satoshiBase_, int32 reserveRatio_, uint16 multiplier_) payable { _rootUser = payable(msg.sender); _rootKey = keccak256(abi.encodePacked(sentence)); _satoshiBase = satoshiBase_; _reserveRatio = reserveRatio_; _multiplier = multiplier_; /* * SETUP BTC GATEWAY. */ _nextBankId = 0; _nextCheckId = 0; _nextCoinId = 0; _nextNoteId = 0; } // C A U T I O N ! ! ! // // Don't forget to remove the section below in production to save the system // tokens. /* * ################## * # Mock functions # * ################## */ /* * Get mock coins * -------------- * Create mock coins to the caller * * @param uint256 amount * Amount of coins to create. */ function mockCreateCoins(uint256 amount) external { _users[msg.sender].state = USER_ACTIVE_AND_RESTRICTIONLESS; for (uint256 i=0; i<amount; i++) { _coins[i] = Coin(address(0), i, 0, msg.sender, COIN_ACTIVE_AND_FREE); _nextCoinId++; } } /* * Get mock coins * -------------- * Create mock coins to a foreign user * * @param address user * Address of the user to create mock coins for. * @param uint256 amount * Amount of coins to create. */ function mockCreateUserWithBalance(address user, uint256 amount) external { _users[user].state = USER_ACTIVE_AND_RESTRICTIONLESS; for (uint256 i=0; i<amount; i++) { _coins[i] = Coin(address(0), i, 0, user, COIN_ACTIVE_AND_FREE); _nextCoinId++; } } /* * Mock transaction between users * ------------------------------ * Perform mock transaction between foreign users * * @param address sender * Address of the user to send mock coins from. * @param address target * Address of the user to send mock coins to. * @param uint256 amount * Amount of coins to create. * * @note Please keep in mind, though it's a mock transaction function, it * calls the real inside _transact() function. So sender must have * enough coins to send. The function mockCreateCoins() is useful to * help you out. */ function mockTransact(address sender, address target, uint256 amount) external returns (bool) { return _transact(sender, target, amount); } /* * ######################### * # End of mock functions # * ######################### */ // Don't forget to remove the section above in production to save the system // tokens. // // C A U T I O N ! ! ! /* * ######################## * # System level actions # * ######################## */ /* * Review coin supply * ------------------ * Review the coin supply of the system */ function review() external { _utxoPointer = 0; for (uint16 i=0; i < _nextBankId; i++) __reviewBank(i); __reviewCoins(); } /* * Set system admin name * --------------------- * Set the name of the system's admin * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newAdmin * The new name of the admin. */ function setAdmin(string calldata sentence, string calldata newAdmin) onlyAdmin(sentence) external { admin = newAdmin; } /* * Set system API root * ------------------- * Set the link to the system's API root * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newApi * The new link to the API root. */ function setApi(string calldata sentence, string calldata newApi) onlyAdmin(sentence) external { api = newApi; } /* * Set system explorer * ------------------- * Set the link to the system's data explorer * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newExplorer * The new link to the explorer. */ function setExplorer(string calldata sentence, string calldata newExplorer) onlyAdmin(sentence) external { explorer = newExplorer; } /* * Set multiplier * -------------- * Set the value of the system's multiplier * * @param string calldata sentence * A sentence to protect master access. * @param uint16 newMultiplier_ * The new multiplier value. */ function setMultiplier(string calldata sentence, uint16 newMultiplier_) onlyAdmin(sentence) external { _multiplier = newMultiplier_; this.review(); } /* * Set system name * -------------- * Set the name of the system * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newName * The new name of the system. */ function setName(string calldata sentence, string calldata newName) onlyAdmin(sentence) external { name = newName; } /* * Set reserve ratio * ----------------- * Set the value of the system's reserve ratio * * @param string calldata sentence * A sentence to protect master access. * @param int32 newReserveRatio_ * The new reserve ratio value. * * @note Since solidity doesn't handle fractions, to set the percentage * value you have to multiply the original (fraction) value with 100. */ function setReserveRatio(string calldata sentence, int32 newReserveRatio_) onlyAdmin(sentence) external { _reserveRatio = newReserveRatio_; this.review(); } /* * Set satoshi base * ---------------- * Set the value of the system's Satoshi base * * @param string calldata sentence * A sentence to protect master access. * @param uint256 newSatoshiBase_ * The new Satoshi base value. */ function setSatoshiBase(string calldata sentence, uint256 newSatoshiBase_) onlyAdmin(sentence) external { _satoshiBase = newSatoshiBase_; this.review(); } /* * Set system homepage * ------------------- * Set the link to the system's homepage * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newSite * The new link to the homepage. */ function setSite(string calldata sentence, string calldata newSite) onlyAdmin(sentence) external { site = newSite; } /* * Set token symbol * ---------------- * Set the symbol of the system's token * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newSymbol * The new symbol of the token. */ function setSymbol(string calldata sentence, string calldata newSymbol) onlyAdmin(sentence) external { symbol = newSymbol; } /* * Set token name * -------------- * Set the name of the system's token * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newToken * The new name of the token. */ function setToken(string calldata sentence, string calldata newToken) onlyAdmin(sentence) external { token = newToken; } /* * ############################ * # System level information # * ############################ */ /* * Get multiplier * -------------- * Get the value of the system's multiplier * * @return uint16 * The actual multiplier value. */ function getMultiplier() external view returns (uint16) { return _multiplier; } /* * Get reserve ratio * ----------------- * Get the value of the system's reserve ratio * * @return int32 * The actual reserve ratio value. * * @note Since solidity doesn't handle fractions, to receive the percentage * value you have to divide the returned value with 100. */ function getReserveRatio() external view returns (int32) { return _reserveRatio; } /* * Get satoshi base * ---------------- * Get the value of the system's Satoshi base * * @return uint256 * The actual Satoshi base value. */ function getSatoshiBase() external view returns (uint256) { return _satoshiBase; } /* * Get active coin count * --------------------- * Get the count of active coins in the system * * @return uint256 * The actual count of active coins. */ function getCoinCount() external view returns (uint256) { uint256 result = 0; for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].state == COIN_ACTIVE_AND_FREE || _coins[i].state == COIN_ACTIVE_IN_CHECK || _coins[i].state == COIN_ACTIVE_IN_NOTE) result++; return result; } /* * ######### * # Banks # * ######### */ //////////// // CREATE // //////////// /* * Create bank * ----------- * Create (register) a bank * * @param string calldata sentence * A sentence to protect master access. * @param string calldata bankName * The name of the bank to register. * @param address mainAccount * An address to be used as the bank's main account. * @param string calldata firstPassPhrase * A password phrase to be used as the first [0] security key. */ function createBank(string calldata sentence, string calldata bankName, address mainAccount, string calldata firstPassPhrase) onlyAdmin(sentence) lockBank(_nextBankId) external returns (uint16) { uint16 thisId = _nextBankId; bytes32[] memory keyArray = new bytes32[] (1); keyArray[0] = keccak256(abi.encodePacked(firstPassPhrase)); _banks[thisId].bank.name = bankName; _banks[thisId].bank.api = ''; _banks[thisId].bank.site = ''; delete _banks[thisId].bank.accountsBTC; _banks[thisId].bank.mainAccount = mainAccount; delete _banks[thisId].bank.accounts; delete _banks[thisId].bank.keys; _banks[thisId].bank.state = BANK_CREATED; _nextBankId++; return thisId; } ////////// // READ // ////////// /* * Get a bank * ---------- * Get data of a bank * * @param uint16 id * ID of the check. * * @return Bank memory * The data of the given bank. * * @note Keys of the bank rest hidden. */ function getBank(uint16 id) external view returns (Bank memory) { bytes32[] memory keyArray = new bytes32[] (0); Bank memory result = _banks[id].bank; result.keys = keyArray; return result; } /* * Get bank count * -------------- * Get the count of all banks. * * @return uin16 * The count of the banks. */ function getBankCount() external view returns (uint16) { return _nextBankId; } /* * Get all banks * ------------- * Get data of all banks * * @return Bank[] memory * List of data of all banks. * * @note Keys of banks rest hidden. */ function getBanks() external view returns (Bank[] memory) { Bank[] memory result = new Bank[](_nextBankId); bytes32[] memory keyArray = new bytes32[] (0); for (uint16 i=0; i < _nextBankId; i++) { result[i] = _banks[i].bank; result[i].keys = keyArray; } return result; } //////////// // UPDATE // //////////// /* * TODO IMPLEMENT * * BTC accounts: * - addBankBTCAccount(uint16 id, string calldata sentence, address btcAccount) * - addBankBTCAccount(uint16 id, uint256 keyId, string calldata passPhrase, address btcAccount) * - activateBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence) * - activateBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * - deleteBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence) * - deleteBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * - suspendBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence) * - suspendBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * * Note: BTC account related functions autamotically call review() * * System accounts: * - addBankAccount(uint16 id, string calldata sentence, address account) * - addBankAccount(uint16 id, uint256 keyId, string calldata passPhrase, address account) * - activateBankAccount(uint16 id, uint256 accountId, string calldata sentence) * - activateBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * - deleteBankAccount(uint16 id, uint256 accountId, string calldata sentence) * - deleteBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * - suspendBankAccount(uint16 id, uint256 accountId, string calldata sentence) * - suspendBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * * - addBankKey(string calldata sentence, string calldata passPhrase) * - addBankKey(uint256 keyId, string calldata passPhrase, string calldata passPhrase) * - changeBankKey(uint16 id, uint256 affectedKeyId, string calldata sentence, string calldata newPassPhrase) * - changeBankKey(uint16 id, uint256 affectedKeyId, uint256 keyId, string calldata passPhrase, string calldata newPassPhrase) * * TODO: CHANGE * * - More complex key validation system. */ /* * Activate bank * ------------- * Activate a non activated bank * * @param uint16 id * The ID of the bank to activate. * @param string calldata sentence * A sentence to protect master access. */ function activateBank(uint16 id, string calldata sentence) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { require(_banks[id].bank.state == BANK_CREATED, 'Cannot activate bank with a non appropriate state.'); _banks[id].bank.state = BANK_ACTIVE_AND_RESTRICTIONLESS; } /* * Set API site link of a bank * --------------------------- * Set the link to the API root of the bank * * @param uint16 id * The ID of the bank. * @param string calldata sentence * A sentence to protect master access. * @param string calldata newApi * The new API site link to set. */ function setBankApi(uint16 id, string calldata sentence, string calldata newApi) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { _banks[id].bank.api = newApi; } /* * Set API site link of a bank * --------------------------- * Set the link to the API root of the bank * * @param uint16 id * The ID of the bank. * @param uint256 keyId * The ID of the key to valIdate transaction with. * @param string calldata passPhrase * A password phrase that matches the key to grant access. * @param string calldata newApi * The new API site link to set. */ function setBankApi(uint16 id, uint256 keyId, string calldata passPhrase, string calldata newApi) onlyExistingBank(id) lockBank(id) onlyValIdBankAction(id, keyId, passPhrase) external { _banks[id].bank.api = newApi; } /* * Set name of a bank * ------------------ * Set the name of the bank * * @param uint16 id * The ID of the bank. * @param string calldata sentence * A sentence to protect master access. * @param string calldata newName * The new name to set. */ function setBankName(uint16 id, string calldata sentence, string calldata newName) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { _banks[id].bank.name = newName; } /* * Set name of a bank * ------------------ * Set the name of the bank * * @param uint16 id * The ID of the bank. * @param uint256 keyId * The ID of the key to valIdate transaction with. * @param string calldata passPhrase * A password phrase that matches the key to grant access. * @param string calldata newName * The new name to set. */ function setBankName(uint16 id, uint256 keyId, string calldata passPhrase, string calldata newName) onlyExistingBank(id) lockBank(id) onlyValIdBankAction(id, keyId, passPhrase) external { _banks[id].bank.name = newName; } /* * Set homepage link of a bank * --------------------------- * Set the link to the homepage of the bank * * @param uint16 id * The ID of the bank. * @param string calldata sentence * A sentence to protect master access. * @param string calldata newSite * The new homepage link to set. */ function setBankSite(uint16 id, string calldata sentence, string calldata newSite) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { _banks[id].bank.site = newSite; } /* * Set homepage link of a bank * --------------------------- * Set the link to the homepage of the bank * * @param uint16 id * The ID of the bank. * @param uint256 keyId * The ID of the key to valIdate transaction with. * @param string calldata passPhrase * A password phrase that matches the key to grant access. * @param string calldata newSite * The new homepage link to set. */ function setBankSite(uint16 id, uint256 keyId, string calldata passPhrase, string calldata newSite) onlyExistingBank(id) lockBank(id) onlyValIdBankAction(id, keyId, passPhrase) external { _banks[id].bank.site = newSite; } /* * Suspend bank * ------------ * Suspend am active bank * * @param uint16 id * The ID of the bank to suspend. * @param string calldata sentence * A sentence to protect master access. */ function suspendBank(uint16 id, string calldata sentence) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { require(_banks[id].bank.state == BANK_SUSPENDED || _banks[id].bank.state == BANK_DELETED, 'Cannot suspend a bank with a non appropriate state.'); _banks[id].bank.state = BANK_SUSPENDED; } //////////// // DELETE // //////////// /* * Delete bank * ----------- * Delete an existing bank * * @param uint16 id * The ID of the bank to delete. * @param string calldata sentence * A sentence to protect master access. */ function deleteBank(uint16 id, string calldata sentence) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { require(_banks[id].bank.state == BANK_DELETED, 'Cannot delete an already deleted bank.'); _banks[id].bank.state = BANK_DELETED; } /* * ########## * # Checks # * ########## */ //////////// // CREATE // //////////// /* * Create check * ------------ * Create a check without activation * * @param uint256 amount * The amount of the check. * @param string memory passPhrase * A pharese to secure the check. */ function createActiveCheck(uint256 amount, string calldata passPhrase) lockUser(msg.sender) external returns (uint256) { return _createCheck(amount, passPhrase, CHECK_ACTIVATED); } /* * Create check * ------------ * Create a check with activation * * @param uint256 amount * The amount of the check. * @param string memory passPhrase * A pharese to secure the check. */ function createCheck(uint256 amount, string calldata passPhrase) lockUser(msg.sender) external returns (uint256) { return _createCheck(amount, passPhrase, CHECK_CREATED); } ////////// // READ // ////////// /* * Get a check * ----------- * Get data of a check * * @param uint256 id * ID of the check. * * @note Check's key is hIdden. This way the key of the check cannot be * retrieved. This design decision pushes big responsibility to the * end-users' application. */ function getCheck(uint256 id) external view returns (Check memory) { return Check(_checks[id].check.owner, _checks[id].check.coins, '', _checks[id].check.state); } /* * Get check value * --------------- * Get the value of a check * * @param uint256 id * ID of the check. * * @return uint256 * The value of the given check. */ function getCheckValue(uint256 id) external view returns (uint256) { return _checks[id].check.coins.length; } //////////// // UPDATE // //////////// /* * Activate check * -------------- * Activate a non activated check * * @param uint256 id * ID of the check. * @param string memory passPhrase * A pharese to secure the check. */ function activateCheck(uint256 id, string calldata passPhrase) lockCheck(id) onlyValIdCheckAction(id, msg.sender, passPhrase) external { require(_checks[id].check.state == CHECK_CREATED || _checks[id].check.state == CHECK_SUSPENDED, 'Cannot activate a check from a non appropriate state.'); _checks[id].check.state = CHECK_ACTIVATED; } /* * Clear check * ----------- * Clear an active check * * @param uint256 id * ID of the check. * @param string memory passPhrase * A pharese to secure the check. */ function clearCeck(uint256 id, address from, string calldata passPhrase) lockUser(msg.sender) lockUser(from) lockCheck(id) onlyValIdCheckAction(id, from, passPhrase) external { require(_checks[id].check.state == CHECK_ACTIVATED, 'Cannot clear a non active check.'); require(_checks[id].check.owner == from, 'Original owner is needed to clear check.'); require(_checks[id].check.key == keccak256(abi.encodePacked(passPhrase)), 'Cannot clear a not opened check.'); // Note: consider to do this after the for loop. It is a hard decision. _checks[id].check.state = CHECK_SPENT; // There's no lack of {}s in the for loop and if selector below. :-) for (uint256 i=0; i < _checks[id].check.coins.length; i++) if (_coins[_checks[id].check.coins[i]].owner != from || _coins[_checks[id].check.coins[i]].state != COIN_ACTIVE_IN_CHECK) revert('Internal error: Check clearance refused, safety first.'); else _coins[_checks[id].check.coins[i]].owner = msg.sender; } /* * Suspend check * ------------- * Suspend an existing and non suspended check * * @param uint256 id * ID of the check. * @param string memory passPhrase * A pharese to secure the check. */ function suspendCheck(uint256 id, string calldata passPhrase) lockCheck(id) onlyValIdCheckAction(id, msg.sender, passPhrase) external { require((_checks[id].check.state == CHECK_CREATED || _checks[id].check.state == CHECK_ACTIVATED), 'Cannot perform suspending on check with non appropriate state.'); _checks[id].check.state = CHECK_SUSPENDED; } //////////// // DELETE // //////////// /* * Delete a check * -------------- * Delete a not yet cleared check * * @param uint256 id * ID of the check. * @param string memory passPhrase * A pharese to secure the check. */ function deleteCheck(uint256 id, string calldata passPhrase) lockCheck(id) onlyValIdCheckAction(id, msg.sender, passPhrase) external { require((_checks[id].check.state == CHECK_CREATED || _checks[id].check.state == CHECK_ACTIVATED || _checks[id].check.state == CHECK_SUSPENDED), 'Cannot perform deletioon on check with non appropriate state.'); // There's no lack of {} in the for loop below. :-) for (uint i=0; i < _checks[id].check.coins.length; i++) _coins[_checks[id].check.coins[i]].state = COIN_ACTIVE_AND_FREE; _checks[id].check.state = CHECK_DELETED; } /* * ######### * # Notes # * ######### */ // TODO: IMPLEMENT /* * ############## * # Note types # * ############## */ // TODO: IMPLEMENT /* * ############################### * # User balance and user coins # * ############################### */ /* * Get the balance of a user * ------------------------- * Get the total balance of a user * * @param address owner * The address of the user to get balance for. * * @return uint256 * The balance of the user. */ function getBalance(address owner) external view returns (uint256) { uint256 result = 0; // There's no lack of {} in the for loop below. :-) for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == owner) result += 1; return result; } /* * Get the coins of a user * ----------------------- * Get the list of all coins of a user * * @param address owner * The address of the user to get coins for. * * @return uint256[] * List if IDs of the coins of the user. */ function getCoins(address owner) external view returns (uint256[] memory) { // Becuse .push() is not available on memory arrays, a non-gas-friendly // workaround should be used. uint256 counter = 0; // There's no lack of {} in the for loop below. :-) for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == owner) counter++; uint256[] memory result = new uint256[](counter); counter = 0; // There's no lack of {} in the for loop below. :-) for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == owner) { result[counter] = i; counter++; } return result; } /* * ################ * # TRANSACTIONS # * ################ */ /* * Transact between users * ---------------------- * Perform transaction between users * * @param address target * Target address to send coins to. * @param uint256 amount * Amount of coins to send. * * @return bool * True if the transaction was successful, false if not. * * @note In most cases like ERC20 token standard event is imetted on * successful transactions. In this ecosystem the function transact() * is called by MNextUser contract, therefore it is more convenient * to return bool instead of emitting an event. Emitting event can * happen in the user's contract depending on the implementation. */ function transact(address target, uint256 amount) lockUser(msg.sender) lockUser(target) external returns (bool) { return _transact(msg.sender, target, amount); } /* * Transact between banks * ---------------------- * Perform transaction between banks * * @param uint16 id * ID of a bank to transact from. * @param uint256 keyId * The ID of the key to valIdate transaction with. * @param string calldata passPhrase * A password phrase that matches the key to grant access. * @param uint16 target * ID of a bank to transact to. * @param uint256 amount * Amount of coins to send. * * @return bool * True if the transaction was successful, false if not. * * @note In most cases like ERC20 token standard event is imetted on * successful transactions. In this ecosystem the function transact() * is called by MNextBank contract, therefore it is more convenient * to return bool instead of emitting an event. Emitting event can * happen in the bank's contract depending on the implementation. */ function transactBankToBank(uint16 id, uint256 keyId, string calldata passPhrase, uint16 target, uint256 amount) onlyExistingBank(id) lockBank(id) onlyValIdBankAction(id, keyId, passPhrase) onlyExistingBank(target) lockBank(target) external returns (bool) { return _transact(_banks[id].bank.mainAccount, _banks[target].bank.mainAccount, amount); } /* * Transact from bank to user * -------------------------- * Perform transaction from a bank to a user * * @param uint16 id * ID of a bank to transact from. * @param uint256 keyId * The ID of the key to valIdate transaction with. * @param string calldata passPhrase * A password phrase that matches the key to grant access. * @param address target * Target address to send coins to. * @param uint256 amount * Amount of coins to send. * * @return bool * True if the transaction was successful, false if not. * * @note In most cases like ERC20 token standard event is imetted on * successful transactions. In this ecosystem the function transact() * is called by MNextBank contract, therefore it is more convenient * to return bool instead of emitting an event. Emitting event can * happen in the bank's contract depending on the implementation. */ function transactBankToUser(uint16 id, uint256 keyId, string calldata passPhrase, address target, uint256 amount) onlyExistingBank(id) lockBank(id) onlyValIdBankAction(id, keyId, passPhrase) onlyExistingUser(target) lockUser(target) external returns (bool) { return _transact(_banks[id].bank.mainAccount, target, amount); } /* * Transact from user to bank * -------------------------- * Perform transaction from a user to a bank * * @param uint16 target * ID of a bank to transact to. * @param uint256 amount * Amount of coins to send. * * @return bool * True if the transaction was successful, false if not. * * @note In most cases like ERC20 token standard event is imetted on * successful transactions. In this ecosystem the function transact() * is called by MNextUser contract, therefore it is more convenient * to return bool instead of emitting an event. Emitting event can * happen in the user's contract depending on the implementation. */ function transactUserToBank(uint16 target, uint256 amount) lockUser(msg.sender) lockBank(target) external returns (bool) { return _transact(msg.sender, _banks[target].bank.mainAccount, amount); } // TODO: IMPLEMENT if bank want to use other than mainAccount both for // bank->bank, bank->user and user->bank transactions. /* * ###################### * # INTERNAL FUNCTIONS # * ###################### */ /* * Create check with state * ----------------------- * Create a check with the given state * * @param uint256 amount * The amount of the check. * @param string memory passPhrase * A pharese to secure the check. * @param uint8 state * The state to create check with. */ function _createCheck(uint256 amount, string calldata passPhrase, uint8 state) lockCheck(_nextCheckId) private returns (uint256) { // Becuse .push() is not available on memory arrays, a non-gas-friendly // workaround should be used. uint256 counter = 0; // There's no lack of {} in the for loop below. :-) for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == msg.sender && _coins[i].state == COIN_ACTIVE_AND_FREE) counter++; require(counter >= amount, 'Not enough balance to create chekk.'); uint256[] memory coins = new uint256[](counter); counter = 0; for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == msg.sender && _coins[i].state == COIN_ACTIVE_AND_FREE) { _coins[i].state = COIN_ACTIVE_IN_CHECK; coins[counter] = i; counter++; if (counter > amount) break; } uint256 _thisId = _nextCheckId; if (_checks[_thisId].isLocked) revert('Internal error: Check creation refused, safety first.'); _checks[_thisId].check = Check(msg.sender, coins, keccak256(abi.encodePacked(passPhrase)), state); _nextCheckId++; return _thisId; } /* * Transact * -------- * Perform transaction between addresses * * @param address owner * Target address to send coins from. * @param address target * Target address to send coins to. * @param uint256 amount * Amount of coins to send. * * @return bool * True if the transaction was successful, false if not. */ function _transact(address owner, address target, uint256 amount) internal returns (bool) { bool result = false; uint256[] memory coinSupply = new uint256[] (amount); uint256 counter = 0; for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == owner && _coins[i].state == COIN_ACTIVE_AND_FREE) { coinSupply[counter] = i; counter++; if (counter == amount) { result = true; break; } } if (result) { for (uint256 i=0; i < coinSupply.length; i++) _coins[i].owner = target; } return result; } /* * ##################### * # PRIVATE FUNCTIONS # * ##################### */ /* * Review utxo deposits of a bank * ------------------------------ * Collects information about presenting utxo deposits of the given bank * * @param uint16 id * The ID of the bank to review. */ function __reviewBank(uint16 id) onlyExistingBank(id) lockBank(id) private { for (uint256 i=0; i<_banks[id].bank.accountsBTC.length; i++) { /* * ACCES BTC GATEWAY. */ uint256 responseLength = 0; address[] memory utxoList = new address[] (responseLength); uint256[] memory amountList = new uint256[] (responseLength); require(utxoList.length == amountList.length, 'BTC gateway error.'); for (uint256 j=0; j < utxoList.length; j++) { _utxos[_utxoPointer] = BTCutxo(utxoList[j], amountList[j], id, i); _utxoPointer++; } } } /* * Review all the system coins * --------------------------- * Review system coins whether hey have the needed BTC deposits or not */ function __reviewCoins() private { // HOW IT WORKS? // 1. Gets all available utxos // 2. Loops over coins and marks missing utxos // 3. If there are coins without deposits, attempts to swap or delete them // 4. If there are utxos without coins, they might used to coin swap // 5. If there are utxos withoot coins after swaps, attempts to create coins // 6. If something important happen in this functions events are mitted } /* * ############# * # MODIFIERS # * ############# */ /* * Lock a bank * ----------- * Attempt to lock a bank during its data gets changed * * @param uint16 id * The ID of the bank to lock. */ modifier lockBank(uint16 id) { require(!_banks[id].isLocked, 'Cannot perform action on a locked bank.'); _banks[id].isLocked = true; _; _banks[id].isLocked = false; } /* * Lock a check * ------------ * Attempt to lock a check during its data gets changed * * @param uint256 id * The ID of the check to lock. */ modifier lockCheck(uint256 id) { require(!_checks[id].isLocked, 'Cannot perform action on a locked check.'); _checks[id].isLocked = true; _; _checks[id].isLocked = false; } /* * Lock a user * ----------- * Attempt to lock a user during its data gets changed * * @param address wallet * The wallet of the user to lock. */ modifier lockUser(address wallet) { require(!_users[wallet].isLocked, 'Cannot perform action on a locked user.'); _users[wallet].isLocked = true; _; _users[wallet].isLocked = false; } /* * ValIdate admin * -------------- * ValIdate access of the master contract owner * * @param string memory sentence * A sentence to protect master access. */ modifier onlyAdmin(string memory sentence) { require(msg.sender == _rootUser, 'Only admin can perform the action.'); require(keccak256(abi.encodePacked(sentence)) == _rootKey, 'Authorization failed.'); _; } /* * Check existence of a bank * ------------------------- * Check whether a bank exists or not * * @param uint16 id * The ID of the bank to check. */ modifier onlyExistingBank(uint16 id) { require(_banks[id].bank.state != STATE_UNAVAILABLE, 'Bank id must exist.'); _; } /* * Check existence of a check * -------------------------- * Check whether a check exists or not * * @param uint256 id * The ID of the check to check. */ modifier onlyExistingCheck(uint256 id) { require(_checks[id].check.state != STATE_UNAVAILABLE, 'Check id must exist.'); _; } /* * Check existence of a coin * ------------------------- * Check whether a coin exists or not * * @param uint256 id * The ID of the coin to check. */ modifier onlyExistingCoin(uint256 id) { require(_coins[id].state != STATE_UNAVAILABLE, 'Coin id must exist.'); _; } /* * Check existence of a note * ------------------------- * Check whether a note exists or not * * @param uint256 id * The ID of the note to check. */ modifier onlyExistingNote(uint256 id) { require(_notes[id].state != STATE_UNAVAILABLE, 'Note id must exist.'); _; } /* * Check existence of a user * ------------------------- * Check whether a user exists locally or not * * @param address who * The address of the user to check. */ modifier onlyExistingUser(address who) { require(_users[who].state != STATE_UNAVAILABLE && _users[who].state != USER_DELETED, 'User must exist.'); _; } modifier onlyValIdBankAction(uint16 id, uint256 keyId, string calldata passPhrase) { require(_banks[id].bank.keys.length < keyId, 'Cannot valIdate a non existing key.'); require(_banks[id].bank.keys[keyId] == keccak256(abi.encodePacked(passPhrase)), 'Authorization failed.'); _; } /* * ValIdate check access * --------------------- * ValIdate access credentials to perform actions on a check * * @param uint256 id * ID of the check. * @param address owner * The address of owner of the check. * @param string memory passPhrase * A pharese to secure the check. */ modifier onlyValIdCheckAction(uint256 id, address owner, string calldata passPhrase) { require(_checks[id].check.owner == owner, 'Cannot perform action on a foreign check.'); require(_checks[id].check.key == keccak256(abi.encodePacked(passPhrase)), 'Cannot perform action on a not opened check.'); _; } }
Get all banks ------------- Get data of all banks return Bank[] memory List of data of all banks. @note Keys of banks rest hidden./
function getBanks() external view returns (Bank[] memory) { Bank[] memory result = new Bank[](_nextBankId); bytes32[] memory keyArray = new bytes32[] (0); for (uint16 i=0; i < _nextBankId; i++) { result[i] = _banks[i].bank; result[i].keys = keyArray; } return result; }
2,507,080
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // library SafeMath { function ADD864(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB868(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB868(a, b, "SafeMath: subtraction overflow"); } function SUB868(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL988(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV926(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV926(a, b, "SafeMath: division by zero"); } function DIV926(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD713(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD713(a, b, "SafeMath: modulo by zero"); } function MOD713(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function SAFEAPPROVE567(address token, address to, uint value) internal { //inject NONSTANDARD NAMING // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function SAFETRANSFER962(address token, address to, uint value) internal { //inject NONSTANDARD NAMING // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function SAFETRANSFERFROM567(address token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function SAFETRANSFERETH46(address to, uint value) internal { //inject NONSTANDARD NAMING (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // library Math { function MAX98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN757(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE252(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // 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_entered371 = 1; //inject NONSTANDARD NAMING uint256 private constant _entered907 = 2; //inject NONSTANDARD NAMING uint256 private _status; constructor () internal { _status = _not_entered371; } modifier NONREENTRANT361() { //inject NONSTANDARD NAMING // On the first call to nonReentrant, _notEntered will be true require(_status != _entered907, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _entered907; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _not_entered371; } } // interface ICoFiXStakingRewards { // Views function REWARDSVAULT139() external view returns (address); //inject NONSTANDARD NAMING function LASTBLOCKREWARDAPPLICABLE573() external view returns (uint256); //inject NONSTANDARD NAMING function REWARDPERTOKEN122() external view returns (uint256); //inject NONSTANDARD NAMING function EARNED893(address account) external view returns (uint256); //inject NONSTANDARD NAMING function ACCRUED168() external view returns (uint256); //inject NONSTANDARD NAMING function REWARDRATE36() external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING function STAKINGTOKEN641() external view returns (address); //inject NONSTANDARD NAMING function REWARDSTOKEN657() external view returns (address); //inject NONSTANDARD NAMING // Mutative function STAKE225(uint256 amount) external; //inject NONSTANDARD NAMING function STAKEFOROTHER357(address other, uint256 amount) external; //inject NONSTANDARD NAMING function WITHDRAW360(uint256 amount) external; //inject NONSTANDARD NAMING function EMERGENCYWITHDRAW536() external; //inject NONSTANDARD NAMING function GETREWARD438() external; //inject NONSTANDARD NAMING function GETREWARDANDSTAKE43() external; //inject NONSTANDARD NAMING function EXIT912() external; //inject NONSTANDARD NAMING function ADDREWARD881(uint256 amount) external; //inject NONSTANDARD NAMING // Events event REWARDADDED378(address sender, uint256 reward); //inject NONSTANDARD NAMING event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING } // interface ICoFiXVaultForLP { enum POOL_STATE {INVALID, ENABLED, DISABLED} event NEWPOOLADDED559(address pool, uint256 index); //inject NONSTANDARD NAMING event POOLENABLED434(address pool); //inject NONSTANDARD NAMING event POOLDISABLED539(address pool); //inject NONSTANDARD NAMING function SETGOVERNANCE394(address _new) external; //inject NONSTANDARD NAMING function SETINITCOFIRATE698(uint256 _new) external; //inject NONSTANDARD NAMING function SETDECAYPERIOD166(uint256 _new) external; //inject NONSTANDARD NAMING function SETDECAYRATE667(uint256 _new) external; //inject NONSTANDARD NAMING function ADDPOOL220(address pool) external; //inject NONSTANDARD NAMING function ENABLEPOOL504(address pool) external; //inject NONSTANDARD NAMING function DISABLEPOOL836(address pool) external; //inject NONSTANDARD NAMING function SETPOOLWEIGHT937(address pool, uint256 weight) external; //inject NONSTANDARD NAMING function BATCHSETPOOLWEIGHT100(address[] memory pools, uint256[] memory weights) external; //inject NONSTANDARD NAMING function DISTRIBUTEREWARD70(address to, uint256 amount) external; //inject NONSTANDARD NAMING function GETPENDINGREWARDOFLP590(address pair) external view returns (uint256); //inject NONSTANDARD NAMING function CURRENTPERIOD82() external view returns (uint256); //inject NONSTANDARD NAMING function CURRENTCOFIRATE163() external view returns (uint256); //inject NONSTANDARD NAMING function CURRENTPOOLRATE277(address pool) external view returns (uint256 poolRate); //inject NONSTANDARD NAMING function CURRENTPOOLRATEBYPAIR255(address pair) external view returns (uint256 poolRate); //inject NONSTANDARD NAMING function STAKINGPOOLFORPAIR714(address pair) external view returns (address pool); //inject NONSTANDARD NAMING function GETPOOLINFO427(address pool) external view returns (POOL_STATE state, uint256 weight); //inject NONSTANDARD NAMING function GETPOOLINFOBYPAIR166(address pair) external view returns (POOL_STATE state, uint256 weight); //inject NONSTANDARD NAMING function GETENABLEDPOOLCNT412() external view returns (uint256); //inject NONSTANDARD NAMING function GETCOFISTAKINGPOOL12() external view returns (address pool); //inject NONSTANDARD NAMING } // interface IERC20 { function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER204(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE758(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE960(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM982(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER211(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL330(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // interface ICoFiStakingRewards { // Views function REWARDPERTOKEN122() external view returns (uint256); //inject NONSTANDARD NAMING function EARNED893(address account) external view returns (uint256); //inject NONSTANDARD NAMING function ACCRUED168() external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING function STAKINGTOKEN641() external view returns (address); //inject NONSTANDARD NAMING function REWARDSTOKEN657() external view returns (address); //inject NONSTANDARD NAMING // Mutative function STAKE225(uint256 amount) external; //inject NONSTANDARD NAMING function STAKEFOROTHER357(address other, uint256 amount) external; //inject NONSTANDARD NAMING function WITHDRAW360(uint256 amount) external; //inject NONSTANDARD NAMING function EMERGENCYWITHDRAW536() external; //inject NONSTANDARD NAMING function GETREWARD438() external; //inject NONSTANDARD NAMING function ADDETHREWARD660() external payable; //inject NONSTANDARD NAMING function EXIT912() external; //inject NONSTANDARD NAMING // Events event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event SAVINGWITHDRAWN125(address indexed to, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING } // interface ICoFiXFactory { // All pairs: {ETH <-> ERC20 Token} event PAIRCREATED889(address indexed token, address pair, uint256); //inject NONSTANDARD NAMING event NEWGOVERNANCE470(address _new); //inject NONSTANDARD NAMING event NEWCONTROLLER331(address _new); //inject NONSTANDARD NAMING event NEWFEERECEIVER222(address _new); //inject NONSTANDARD NAMING event NEWFEEVAULTFORLP508(address token, address feeVault); //inject NONSTANDARD NAMING event NEWVAULTFORLP769(address _new); //inject NONSTANDARD NAMING event NEWVAULTFORTRADER72(address _new); //inject NONSTANDARD NAMING event NEWVAULTFORCNODE372(address _new); //inject NONSTANDARD NAMING function CREATEPAIR976( //inject NONSTANDARD NAMING address token ) external returns (address pair); function GETPAIR599(address token) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS153(uint256) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH789() external view returns (uint256); //inject NONSTANDARD NAMING function GETTRADEMININGSTATUS473(address token) external view returns (bool status); //inject NONSTANDARD NAMING function SETTRADEMININGSTATUS493(address token, bool status) external; //inject NONSTANDARD NAMING function GETFEEVAULTFORLP473(address token) external view returns (address feeVault); // for LPs //inject NONSTANDARD NAMING function SETFEEVAULTFORLP669(address token, address feeVault) external; //inject NONSTANDARD NAMING function SETGOVERNANCE394(address _new) external; //inject NONSTANDARD NAMING function SETCONTROLLER726(address _new) external; //inject NONSTANDARD NAMING function SETFEERECEIVER908(address _new) external; //inject NONSTANDARD NAMING function SETVAULTFORLP99(address _new) external; //inject NONSTANDARD NAMING function SETVAULTFORTRADER40(address _new) external; //inject NONSTANDARD NAMING function SETVAULTFORCNODE20(address _new) external; //inject NONSTANDARD NAMING function GETCONTROLLER295() external view returns (address controller); //inject NONSTANDARD NAMING function GETFEERECEIVER766() external view returns (address feeReceiver); // For CoFi Holders //inject NONSTANDARD NAMING function GETVAULTFORLP604() external view returns (address vaultForLP); //inject NONSTANDARD NAMING function GETVAULTFORTRADER901() external view returns (address vaultForTrader); //inject NONSTANDARD NAMING function GETVAULTFORCNODE682() external view returns (address vaultForCNode); //inject NONSTANDARD NAMING } // // Stake XToken to earn CoFi Token contract CoFiXStakingRewards is ICoFiXStakingRewards, ReentrancyGuard { using SafeMath for uint256; address public override immutable rewardsToken; // CoFi address public override immutable stakingToken; // XToken or CNode address public immutable factory; uint256 public lastUpdateBlock; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor( address _rewardsToken, address _stakingToken, address _factory ) public { rewardsToken = _rewardsToken; stakingToken = _stakingToken; require(ICoFiXFactory(_factory).GETVAULTFORLP604() != address(0), "VaultForLP not set yet"); // check factory = _factory; lastUpdateBlock = 11040688; // https://etherscan.io/block/countdown/11040688 } // replace cofixVault with rewardsVault, this could introduce more calls, but clear is more important function REWARDSVAULT139() public virtual override view returns (address) { //inject NONSTANDARD NAMING return ICoFiXFactory(factory).GETVAULTFORLP604(); } function TOTALSUPPLY567() external override view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF980(address account) external override view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function LASTBLOCKREWARDAPPLICABLE573() public override view returns (uint256) { //inject NONSTANDARD NAMING return block.number; } function REWARDPERTOKEN122() public override view returns (uint256) { //inject NONSTANDARD NAMING if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.ADD864( ACCRUED168().MUL988(1e18).DIV926(_totalSupply) ); } function _REWARDPERTOKENANDACCRUED426() internal view returns (uint256, uint256) { //inject NONSTANDARD NAMING if (_totalSupply == 0) { // use the old rewardPerTokenStored, and accrued should be zero here // if not the new accrued amount will never be distributed to anyone return (rewardPerTokenStored, 0); } uint256 _accrued = ACCRUED168(); uint256 _rewardPerToken = rewardPerTokenStored.ADD864( _accrued.MUL988(1e18).DIV926(_totalSupply) ); return (_rewardPerToken, _accrued); } function REWARDRATE36() public virtual override view returns (uint256) { //inject NONSTANDARD NAMING return ICoFiXVaultForLP(REWARDSVAULT139()).CURRENTPOOLRATE277(address(this)); } function ACCRUED168() public virtual override view returns (uint256) { //inject NONSTANDARD NAMING // calc block rewards uint256 blockReward = LASTBLOCKREWARDAPPLICABLE573().SUB868(lastUpdateBlock).MUL988(REWARDRATE36()); // query pair trading rewards uint256 tradingReward = ICoFiXVaultForLP(REWARDSVAULT139()).GETPENDINGREWARDOFLP590(stakingToken); return blockReward.ADD864(tradingReward); } function EARNED893(address account) public override view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account].MUL988(REWARDPERTOKEN122().SUB868(userRewardPerTokenPaid[account])).DIV926(1e18).ADD864(rewards[account]); } function STAKE225(uint256 amount) external override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.ADD864(amount); _balances[msg.sender] = _balances[msg.sender].ADD864(amount); TransferHelper.SAFETRANSFERFROM567(stakingToken, msg.sender, address(this), amount); emit STAKED268(msg.sender, amount); } function STAKEFOROTHER357(address other, uint256 amount) external override NONREENTRANT361 UPDATEREWARD178(other) { //inject NONSTANDARD NAMING require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.ADD864(amount); _balances[other] = _balances[other].ADD864(amount); TransferHelper.SAFETRANSFERFROM567(stakingToken, msg.sender, address(this), amount); emit STAKEDFOROTHER964(msg.sender, other, amount); } function WITHDRAW360(uint256 amount) public override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.SUB868(amount); _balances[msg.sender] = _balances[msg.sender].SUB868(amount); TransferHelper.SAFETRANSFER962(stakingToken, msg.sender, amount); emit WITHDRAWN805(msg.sender, amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function EMERGENCYWITHDRAW536() external override NONREENTRANT361 { //inject NONSTANDARD NAMING uint256 amount = _balances[msg.sender]; require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.SUB868(amount); _balances[msg.sender] = 0; rewards[msg.sender] = 0; TransferHelper.SAFETRANSFER962(stakingToken, msg.sender, amount); emit EMERGENCYWITHDRAW7(msg.sender, amount); } function GETREWARD438() public override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; // TransferHelper.safeTransfer(rewardsToken, msg.sender, reward); uint256 transferred = _SAFECOFITRANSFER191(msg.sender, reward); emit REWARDPAID501(msg.sender, transferred); } } // get CoFi rewards and staking into CoFiStakingRewards pool function GETREWARDANDSTAKE43() external override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; address cofiStakingPool = ICoFiXVaultForLP(REWARDSVAULT139()).GETCOFISTAKINGPOOL12(); // also work for VaultForCNode require(cofiStakingPool != address(0), "cofiStakingPool not set"); // approve to staking pool address _rewardsToken = rewardsToken; IERC20(_rewardsToken).APPROVE960(cofiStakingPool, reward); ICoFiStakingRewards(cofiStakingPool).STAKEFOROTHER357(msg.sender, reward); IERC20(_rewardsToken).APPROVE960(cofiStakingPool, 0); // ensure emit REWARDPAID501(msg.sender, reward); } } function EXIT912() external override { //inject NONSTANDARD NAMING WITHDRAW360(_balances[msg.sender]); GETREWARD438(); } // add reward from trading pool or anyone else function ADDREWARD881(uint256 amount) public override NONREENTRANT361 UPDATEREWARD178(address(0)) { //inject NONSTANDARD NAMING // transfer from caller (router contract) TransferHelper.SAFETRANSFERFROM567(rewardsToken, msg.sender, address(this), amount); // update rewardPerTokenStored rewardPerTokenStored = rewardPerTokenStored.ADD864(amount.MUL988(1e18).DIV926(_totalSupply)); emit REWARDADDED378(msg.sender, amount); } // Safe CoFi transfer function, just in case if rounding error or ending of mining causes pool to not have enough CoFis. function _SAFECOFITRANSFER191(address _to, uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING uint256 cofiBal = IERC20(rewardsToken).BALANCEOF980(address(this)); if (_amount > cofiBal) { _amount = cofiBal; } TransferHelper.SAFETRANSFER962(rewardsToken, _to, _amount); // allow zero amount return _amount; } modifier UPDATEREWARD178(address account) virtual { //inject NONSTANDARD NAMING // rewardPerTokenStored = rewardPerToken(); // uint256 newAccrued = accrued(); (uint256 newRewardPerToken, uint256 newAccrued) = _REWARDPERTOKENANDACCRUED426(); rewardPerTokenStored = newRewardPerToken; if (newAccrued > 0) { // distributeReward could fail if CoFiXVaultForLP is not minter of CoFi anymore // Should set reward rate to zero first, and then do a settlement of pool reward by call getReward ICoFiXVaultForLP(REWARDSVAULT139()).DISTRIBUTEREWARD70(address(this), newAccrued); } lastUpdateBlock = LASTBLOCKREWARDAPPLICABLE573(); if (account != address(0)) { rewards[account] = EARNED893(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } event REWARDADDED378(address sender, uint256 reward); //inject NONSTANDARD NAMING event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING }
inject NONSTANDARD NAMING
function REWARDRATE36() public virtual override view returns (uint256) {
1,840,809
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.10; // types import "../types/BaseAllocator.sol"; interface ILendingPool { function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address asset, uint256 amount, address to ) external returns (uint256); } interface IStakedTokenIncentivesController { function claimRewards( address[] memory assets, uint256 amount, address to ) external; function claimRewardsOnBehalf( address[] memory assets, uint256 amount, address user, address to ) external; function getRewardsBalance(address[] memory assets, address user) external view returns (uint256); } contract AaveAllocatorV2 is BaseAllocator { address public constant treasury = 0x9A315BdF513367C0377FB36545857d12e85813Ef; // stkAave incentive controller IStakedTokenIncentivesController public immutable incentives = IStakedTokenIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5); // Aave Lending Pool ILendingPool public immutable pool = ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); IERC20[] internal _aTokens; uint16 public referralCode; constructor(AllocatorInitData memory data) BaseAllocator(data) {} function _update(uint256 id) internal override returns (uint128 gain, uint128 loss) { // reads uint256 tokenId = tokenIds[id]; IERC20 token = _tokens[tokenId]; IERC20 aToken = _aTokens[tokenId]; uint256 balance = token.balanceOf(address(this)); // interactions if (balance > 0) { token.approve(address(pool), balance); pool.deposit(address(token), balance, address(this), referralCode); } uint256 aBalance = aToken.balanceOf(address(this)); uint256 last = extender.getAllocatorAllocated(id) + extender.getAllocatorPerformance(id).gain; // we can do this because aToken is 1:1 with deposited if (aBalance >= last) { gain = uint128(aBalance - last); } else { loss = uint128(last - aBalance); } } function deallocate(uint256[] memory amounts) public override { // checks _onlyGuardian(); for (uint256 i; i < amounts.length; i++) { uint256 amount = amounts[i]; if (amount > 0) { IERC20 token = _tokens[i]; IERC20 aToken = _aTokens[i]; aToken.approve(address(pool), amount); pool.withdraw(address(token), amount, address(this)); } } } function _deactivate(bool panic) internal override { _deallocateAll(); if (panic) { for (uint256 i; i < _tokens.length; i++) { IERC20 token = _tokens[i]; token.transfer(treasury, token.balanceOf(address(this))); } } } function _prepareMigration() internal override {} function amountAllocated(uint256 id) public view override returns (uint256) { return _aTokens[tokenIds[id]].balanceOf(address(this)); } function rewardTokens() public pure override returns (IERC20[] memory) { IERC20[] memory empty = new IERC20[](0); return empty; } function name() external pure override returns (string memory) { return "AaveAllocatorV2"; } function addToken(address token) external { _onlyGuardian(); _tokens.push(IERC20(token)); IERC20(token).approve(address(extender), type(uint256).max); } function addAToken(address aToken) external { _onlyGuardian(); _aTokens.push(IERC20(aToken)); IERC20(aToken).approve(address(extender), type(uint256).max); } function setReferralCode(uint16 code) external { _onlyGuardian(); referralCode = code; } function utilityTokens() public view override returns (IERC20[] memory) { return _aTokens; } function _deallocateAll() internal { // reads uint256[] memory amounts = new uint256[](_tokens.length); // interactions for (uint256 i; i < _tokens.length; i++) { amounts[i] = _aTokens[i].balanceOf(address(this)); } deallocate(amounts); } } pragma solidity ^0.8.10; // interfaces import "../interfaces/IAllocator.sol"; import "../interfaces/ITreasury.sol"; // types import "../types/OlympusAccessControlledV2.sol"; // libraries import "../libraries/SafeERC20.sol"; error BaseAllocator_AllocatorNotActivated(); error BaseAllocator_AllocatorNotOffline(); error BaseAllocator_Migrating(); error BaseAllocator_NotMigrating(); error BaseAllocator_OnlyExtender(address sender); /** * @title BaseAllocator * @notice * This abstract contract serves as a template for writing new Olympus Allocators. * Many of the functionalities regarding handling of Treasury funds by the Guardian have * been delegated to the `TreasuryExtender` contract, and thus an explanation for them can be found * in `TreasuryExtender.sol`. * * The main purpose of this abstract contract and the `IAllocator` interface is to provide * a unified framework for how an Allocator should behave. Below an explanation of how * we expect an Allocator to behave in general, mentioning the most important points. * * Activation: * - An Allocator is first deployed with all necessary arguments. * Thereafter, each deposit is registered with the `TreasuryExtender`. * This assigns a unique id for each deposit (set of allocations) in an Allocator. * - Next, the Allocators allocation and loss limits are set via the extender function. * - Finally, the Allocator is activated by calling `activate`. * * Runtime: * The Allocator is in communication with the Extender, it must inform the Extender * what the status of the tokens is which were allocated. We only care about noting down * their status in the Extender. A quick summary of the important functions on this topic: * * - `update(uint256 id)` is the main function that deals with state reporting, where * `_update(uint256 id)` is the internal function to implement, which should update Allocator * internal state. `update(uint256 id)` then continues to report the Allocators state via `report` * to the extender. `_update(uint256 id)` should handle _investment_ of funds present in Contract. * * - `deallocate` should handle allocated token withdrawal, preparing the tokens to be withdrawn * by the Extender. It is not necessary to handle approvals for this token, because it is automatically * approved in the constructor. For other token withdrawals, it is assumed that reward tokens will * either be sold into underlying (allocated) or that they will simply rest in the Contract, being reward tokens. * Please also check function documentation. * * - `rewardTokens` and `utilityTokens` should return the above mentioned simple reward tokens for the former case, * while utility tokens should be those tokens which are continously reinvested or otherwise used by the contract * in order to accrue more rewards. A reward token can also be a utility token, but then one must prepare them * separately for withdrawal if they are to be returned to the treasury. * * Migration & Deactivation: * - `prepareMigration()` together with the virtual `_prepareMigration()` sets the state of the Allocator into * MIGRATING, disabling further token deposits, enabling only withdrawals, and preparing all funds for withdrawal. * * - `migrate` then executes the migration and also deactivates the Allocator. * * - `deactivate` sets `status` to OFFLINE, meaning it simply deactivates the Allocator. It can be passed * a panic boolean, meaning it handles deactivation logic in `deactivate`. The Allocator panic deactivates if * this state if the loss limit is reached via `update`. The Allocator can otherwise also simply be deactivated * and funds transferred back to the Treasury. * * This was a short summary of the Allocator lifecycle. */ abstract contract BaseAllocator is OlympusAccessControlledV2, IAllocator { using SafeERC20 for IERC20; // Indices which represent the ids of the deposits in the `TreasuryExtender` uint256[] internal _ids; // The allocated (underlying) tokens of the Allocator IERC20[] internal _tokens; // From deposit id to the token's id mapping(uint256 => uint256) public tokenIds; // Allocator status: OFFLINE, ACTIVATED, MIGRATING AllocatorStatus public status; // The extender with which the Allocator communicates. ITreasuryExtender public immutable extender; constructor(AllocatorInitData memory data) OlympusAccessControlledV2(data.authority) { _tokens = data.tokens; extender = data.extender; for (uint256 i; i < data.tokens.length; i++) { data.tokens[i].approve(address(data.extender), type(uint256).max); } emit AllocatorDeployed(address(data.authority), address(data.extender)); } /////// MODIFIERS modifier onlyExtender { _onlyExtender(msg.sender); _; } modifier onlyActivated { _onlyActivated(status); _; } modifier onlyOffline { _onlyOffline(status); _; } modifier notMigrating { _notMigrating(status); _; } modifier isMigrating { _isMigrating(status); _; } /////// VIRTUAL FUNCTIONS WHICH NEED TO BE IMPLEMENTED /////// SORTED BY EXPECTED COMPLEXITY AND DEPENDENCY /** * @notice * Updates an Allocators state. * @dev * This function should be implemented by the developer of the Allocator. * This function should fulfill the following purposes: * - invest token specified by deposit id * - handle rebalancing / harvesting for token as needed * - calculate gain / loss for token and return those values * - handle any other necessary runtime calculations, such as fees etc. * * In essence, this function should update the main runtime state of the Allocator * so that everything is properly invested, harvested, accounted for. * @param id the id of the deposit in the `TreasuryExtender` */ function _update(uint256 id) internal virtual returns (uint128 gain, uint128 loss); /** * @notice * Deallocates tokens, prepares tokens for return to the Treasury. * @dev * This function should deallocate (withdraw) `amounts` of each token so that they may be withdrawn * by the TreasuryExtender. Otherwise, this function may also prepare the withdraw if it is time-bound. * @param amounts is the amount of each of token from `_tokens` to withdraw */ function deallocate(uint256[] memory amounts) public virtual; /** * @notice * Handles deactivation logic for the Allocator. */ function _deactivate(bool panic) internal virtual; /** * @notice * Handles migration preparatory logic. * @dev * Within this function, the developer should arrange the withdrawal of all assets for migration. * A useful function, say, to be passed into this could be `deallocate` with all of the amounts, * so with n places for n-1 utility tokens + 1 allocated token, maxed out. */ function _prepareMigration() internal virtual; /** * @notice * Should estimate total amount of Allocated tokens * @dev * The difference between this and `treasury.getAllocatorAllocated`, is that the latter is a static * value recorded during reporting, but no data is available on _new_ amounts after reporting. * Thus, this should take into consideration the new amounts. This can be used for say aTokens. * @param id the id of the deposit in `TreasuryExtender` */ function amountAllocated(uint256 id) public view virtual returns (uint256); /** * @notice * Should return all reward token addresses */ function rewardTokens() public view virtual returns (IERC20[] memory); /** * @notice * Should return all utility token addresses */ function utilityTokens() public view virtual returns (IERC20[] memory); /** * @notice * Should return the Allocator name */ function name() external view virtual returns (string memory); /////// IMPLEMENTATION OPTIONAL /** * @notice * Should handle activation logic * @dev * If there is a need to handle any logic during activation, this is the function you should implement it into */ function _activate() internal virtual {} /////// FUNCTIONS /** * @notice * Updates an Allocators state and reports to `TreasuryExtender` if necessary. * @dev * Can only be called by the Guardian. * Can only be called while the Allocator is activated. * * This function should update the Allocators internal state via `_update`, which should in turn * return the `gain` and `loss` the Allocator has sustained in underlying allocated `token` from `_tokens` * decided by the `id`. * Please check the docs on `_update` to see what its function should be. * * `_lossLimitViolated` checks if the Allocators is above its loss limit and deactivates it in case * of serious losses. The loss limit should be set to some value which is unnacceptable to be lost * in the case of normal runtime and thus require a panic shutdown, whatever it is defined to be. * * Lastly, the Allocator reports its state to the Extender, which handles gain, loss, allocated logic. * The documentation on this can be found in `TreasuryExtender.sol`. * @param id the id of the deposit in `TreasuryExtender` */ function update(uint256 id) external override onlyGuardian onlyActivated { // effects // handle depositing, harvesting, compounding logic inside of _update() // if gain is in allocated then gain > 0 otherwise gain == 0 // we only use so we know initia // loss always in allocated (uint128 gain, uint128 loss) = _update(id); if (_lossLimitViolated(id, loss)) { deactivate(true); return; } // interactions // there is no interactions happening inside of report // so allocator has no state changes to make after it if (gain + loss > 0) extender.report(id, gain, loss); } /** * @notice * Prepares the Allocator for token migration. * @dev * This function prepares the Allocator for token migration by calling the to-be-implemented * `_prepareMigration`, which should logically withdraw ALL allocated (1) + utility AND reward tokens * from the contract. The ALLOCATED token and THE UTILITY TOKEN is going to be migrated, while the REWARD * tokens can be withdrawn by the Extender to the Treasury. */ function prepareMigration() external override onlyGuardian notMigrating { // effects _prepareMigration(); status = AllocatorStatus.MIGRATING; } /** * @notice * Migrates the allocated and all utility tokens to the next Allocator. * @dev * The allocated token and the utility tokens will be migrated by this function, while it is * assumed that the reward tokens are either simply kept or already harvested into the underlying * essentially being the edge case of this contract. This contract is also going to report to the * Extender that a migration happened and as such it is important to follow the proper sequence of * migrating. * * Steps to migrate: * - FIRST call `_prepareMigration()` to prepare funds for migration. * - THEN deploy the new Allocator and activate it according to the normal procedure. * NOTE: This is to be done RIGHT BEFORE migration as to avoid allocating to the wrong allocator. * - FINALLY call migrate. This is going to migrate the funds to the LAST allocator registered. * - Check if everything went fine. * * End state should be that allocator amounts have been swapped for allocators, that gain + loss is netted out 0 * for original allocator, and that the new allocators gain has been set to the original allocators gain. * We don't transfer the loss because we have the information how much was initially invested + gain, * and the new allocator didn't cause any loss thus we don't really need to add to it. */ function migrate() external override onlyGuardian isMigrating { // reads IERC20[] memory utilityTokensArray = utilityTokens(); address newAllocator = extender.getAllocatorByID(extender.getTotalAllocatorCount() - 1); uint256 idLength = _ids.length; uint256 utilLength = utilityTokensArray.length; // interactions for (uint256 i; i < idLength; i++) { IERC20 token = _tokens[i]; token.safeTransfer(newAllocator, token.balanceOf(address(this))); extender.report(_ids[i], type(uint128).max, type(uint128).max); } for (uint256 i; i < utilLength; i++) { IERC20 utilityToken = utilityTokensArray[i]; utilityToken.safeTransfer(newAllocator, utilityToken.balanceOf(address(this))); } // turn off Allocator deactivate(false); emit MigrationExecuted(newAllocator); } /** * @notice * Activates the Allocator. * @dev * Only the Guardian can call this. * * Add any logic you need during activation, say interactions with Extender or something else, * in the virtual method `_activate`. */ function activate() external override onlyGuardian onlyOffline { // effects _activate(); status = AllocatorStatus.ACTIVATED; emit AllocatorActivated(); } /** * @notice * Adds a deposit ID to the Allocator. * @dev * Only the Extender calls this. * @param id id to add to the allocator */ function addId(uint256 id) external override onlyExtender { _ids.push(id); tokenIds[id] = _ids.length - 1; } /** * @notice * Returns all deposit IDs registered with the Allocator. * @return the deposit IDs registered */ function ids() external view override returns (uint256[] memory) { return _ids; } /** * @notice * Returns all tokens registered with the Allocator. * @return the tokens */ function tokens() external view override returns (IERC20[] memory) { return _tokens; } /** * @notice * Deactivates the Allocator. * @dev * Only the Guardian can call this. * * Add any logic you need during deactivation, say interactions with Extender or something else, * in the virtual method `_deactivate`. Be careful to specifically use the internal or public function * depending on what you need. * @param panic should panic logic be executed */ function deactivate(bool panic) public override onlyGuardian { // effects _deactivate(panic); status = AllocatorStatus.OFFLINE; emit AllocatorDeactivated(panic); } /** * @notice * Getter for Allocator version. * @return Returns the Allocators version. */ function version() public pure override returns (string memory) { return "v2.0.0"; } /** * @notice * Internal check if the loss limit has been violated by the Allocator. * @dev * Called as part of `update`. The rule is that the already sustained loss + newly sustained * has to be larger or equal to the limit to break the contract. * @param id deposit id as in `TreasuryExtender` * @param loss the amount of newly sustained loss * @return true if the the loss limit has been broken */ function _lossLimitViolated(uint256 id, uint128 loss) internal returns (bool) { // read uint128 lastLoss = extender.getAllocatorPerformance(id).loss; // events if ((loss + lastLoss) >= extender.getAllocatorLimits(id).loss) { emit LossLimitViolated(lastLoss, loss, amountAllocated(tokenIds[id])); return true; } return false; } /** * @notice * Internal check to see if sender is extender. */ function _onlyExtender(address sender) internal view { if (sender != address(extender)) revert BaseAllocator_OnlyExtender(sender); } /** * @notice * Internal check to see if allocator is activated. */ function _onlyActivated(AllocatorStatus inputStatus) internal pure { if (inputStatus != AllocatorStatus.ACTIVATED) revert BaseAllocator_AllocatorNotActivated(); } /** * @notice * Internal check to see if allocator is offline. */ function _onlyOffline(AllocatorStatus inputStatus) internal pure { if (inputStatus != AllocatorStatus.OFFLINE) revert BaseAllocator_AllocatorNotOffline(); } /** * @notice * Internal check to see if allocator is not migrating. */ function _notMigrating(AllocatorStatus inputStatus) internal pure { if (inputStatus == AllocatorStatus.MIGRATING) revert BaseAllocator_Migrating(); } /** * @notice * Internal check to see if allocator is migrating. */ function _isMigrating(AllocatorStatus inputStatus) internal pure { if (inputStatus != AllocatorStatus.MIGRATING) revert BaseAllocator_NotMigrating(); } } pragma solidity >=0.8.0; // interfaces import "./IERC20.sol"; import "./ITreasuryExtender.sol"; import "./IOlympusAuthority.sol"; enum AllocatorStatus { OFFLINE, ACTIVATED, MIGRATING } struct AllocatorInitData { IOlympusAuthority authority; ITreasuryExtender extender; IERC20[] tokens; } /** * @title Interface for the BaseAllocator * @dev * These are the standard functions that an Allocator should implement. A subset of these functions * is implemented in the `BaseAllocator`. Similar to those implemented, if for some reason the developer * decides to implement a dedicated base contract, or not at all and rather a dedicated Allocator contract * without base, imitate the functionalities implemented in it. */ interface IAllocator { /** * @notice * Emitted when the Allocator is deployed. */ event AllocatorDeployed(address authority, address extender); /** * @notice * Emitted when the Allocator is activated. */ event AllocatorActivated(); /** * @notice * Emitted when the Allocator is deactivated. */ event AllocatorDeactivated(bool panic); /** * @notice * Emitted when the Allocators loss limit is violated. */ event LossLimitViolated(uint128 lastLoss, uint128 dloss, uint256 estimatedTotalAllocated); /** * @notice * Emitted when a Migration is executed. * @dev * After this also `AllocatorDeactivated` should follow. */ event MigrationExecuted(address allocator); /** * @notice * Emitted when Ether is received by the contract. * @dev * Only the Guardian is able to send the ether. */ event EtherReceived(uint256 amount); function update(uint256 id) external; function deallocate(uint256[] memory amounts) external; function prepareMigration() external; function migrate() external; function activate() external; function deactivate(bool panic) external; function addId(uint256 id) external; function name() external view returns (string memory); function ids() external view returns (uint256[] memory); function tokenIds(uint256 id) external view returns (uint256); function version() external view returns (string memory); function status() external view returns (AllocatorStatus); function tokens() external view returns (IERC20[] memory); function utilityTokens() external view returns (IERC20[] memory); function rewardTokens() external view returns (IERC20[] memory); function amountAllocated(uint256 id) external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity >=0.7.5; interface ITreasury { function deposit( uint256 _amount, address _token, uint256 _profit ) external returns (uint256); function withdraw(uint256 _amount, address _token) external; function tokenValue(address _token, uint256 _amount) external view returns (uint256 value_); function mint(address _recipient, uint256 _amount) external; function manage(address _token, uint256 _amount) external; function incurDebt(uint256 amount_, address token_) external; function repayDebtWithReserve(uint256 amount_, address token_) external; function excessReserves() external view returns (uint256); function baseSupply() external view returns (uint256); } pragma solidity ^0.8.10; import "../interfaces/IOlympusAuthority.sol"; error UNAUTHORIZED(); error AUTHORITY_INITIALIZED(); /// @dev Reasoning for this contract = modifiers literaly copy code /// instead of pointing towards the logic to execute. Over many /// functions this bloats contract size unnecessarily. /// imho modifiers are a meme. abstract contract OlympusAccessControlledV2 { /* ========== EVENTS ========== */ event AuthorityUpdated(IOlympusAuthority authority); /* ========== STATE VARIABLES ========== */ IOlympusAuthority public authority; /* ========== Constructor ========== */ constructor(IOlympusAuthority _authority) { authority = _authority; emit AuthorityUpdated(_authority); } /* ========== "MODIFIERS" ========== */ modifier onlyGovernor { _onlyGovernor(); _; } modifier onlyGuardian { _onlyGuardian(); _; } modifier onlyPolicy { _onlyPolicy(); _; } modifier onlyVault { _onlyVault(); _; } /* ========== GOV ONLY ========== */ function initializeAuthority(IOlympusAuthority _newAuthority) internal { if (authority != IOlympusAuthority(address(0))) revert AUTHORITY_INITIALIZED(); authority = _newAuthority; emit AuthorityUpdated(_newAuthority); } function setAuthority(IOlympusAuthority _newAuthority) external { _onlyGovernor(); authority = _newAuthority; emit AuthorityUpdated(_newAuthority); } /* ========== INTERNAL CHECKS ========== */ function _onlyGovernor() internal view { if (msg.sender != authority.governor()) revert UNAUTHORIZED(); } function _onlyGuardian() internal view { if (msg.sender != authority.guardian()) revert UNAUTHORIZED(); } function _onlyPolicy() internal view { if (msg.sender != authority.policy()) revert UNAUTHORIZED(); } function _onlyVault() internal view { if (msg.sender != authority.vault()) revert UNAUTHORIZED(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.7.5; import {IERC20} from "../interfaces/IERC20.sol"; /// @notice Safe IERC20 and ETH transfer library that safely handles missing return values. /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/TransferHelper.sol) /// Taken from Solmate library SafeERC20 { function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FROM_FAILED"); } function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.transfer.selector, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED"); } function safeApprove( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.approve.selector, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED"); } function safeTransferETH(address to, uint256 amount) internal { (bool success, ) = to.call{value: amount}(new bytes(0)); require(success, "ETH_TRANSFER_FAILED"); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity >=0.7.5; 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); } pragma solidity ^0.8.10; struct AllocatorPerformance { uint128 gain; uint128 loss; } struct AllocatorLimits { uint128 allocated; uint128 loss; } struct AllocatorHoldings { uint256 allocated; } struct AllocatorData { AllocatorHoldings holdings; AllocatorLimits limits; AllocatorPerformance performance; } /** * @title Interface for the TreasuryExtender */ interface ITreasuryExtender { /** * @notice * Emitted when a new Deposit is registered. */ event NewDepositRegistered(address allocator, address token, uint256 id); /** * @notice * Emitted when an Allocator is funded */ event AllocatorFunded(uint256 id, uint256 amount, uint256 value); /** * @notice * Emitted when allocated funds are withdrawn from an Allocator */ event AllocatorWithdrawal(uint256 id, uint256 amount, uint256 value); /** * @notice * Emitted when rewards are withdrawn from an Allocator */ event AllocatorRewardsWithdrawal(address allocator, uint256 amount, uint256 value); /** * @notice * Emitted when an Allocator reports a gain */ event AllocatorReportedGain(uint256 id, uint128 gain); /** * @notice * Emitted when an Allocator reports a loss */ event AllocatorReportedLoss(uint256 id, uint128 loss); /** * @notice * Emitted when an Allocator reports a migration */ event AllocatorReportedMigration(uint256 id); /** * @notice * Emitted when an Allocator limits are modified */ event AllocatorLimitsChanged(uint256 id, uint128 allocationLimit, uint128 lossLimit); function registerDeposit(address newAllocator) external; function setAllocatorLimits(uint256 id, AllocatorLimits memory limits) external; function report( uint256 id, uint128 gain, uint128 loss ) external; function requestFundsFromTreasury(uint256 id, uint256 amount) external; function returnFundsToTreasury(uint256 id, uint256 amount) external; function returnRewardsToTreasury( uint256 id, address token, uint256 amount ) external; function getTotalAllocatorCount() external view returns (uint256); function getAllocatorByID(uint256 id) external view returns (address); function getAllocatorAllocated(uint256 id) external view returns (uint256); function getAllocatorLimits(uint256 id) external view returns (AllocatorLimits memory); function getAllocatorPerformance(uint256 id) external view returns (AllocatorPerformance memory); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity >=0.7.5; interface IOlympusAuthority { /* ========== EVENTS ========== */ event GovernorPushed(address indexed from, address indexed to, bool _effectiveImmediately); event GuardianPushed(address indexed from, address indexed to, bool _effectiveImmediately); event PolicyPushed(address indexed from, address indexed to, bool _effectiveImmediately); event VaultPushed(address indexed from, address indexed to, bool _effectiveImmediately); event GovernorPulled(address indexed from, address indexed to); event GuardianPulled(address indexed from, address indexed to); event PolicyPulled(address indexed from, address indexed to); event VaultPulled(address indexed from, address indexed to); /* ========== VIEW ========== */ function governor() external view returns (address); function guardian() external view returns (address); function policy() external view returns (address); function vault() external view returns (address); }
/ FUNCTIONS Updates an Allocators state and reports to `TreasuryExtender` if necessary. Can only be called by the Guardian. Can only be called while the Allocator is activated. This function should update the Allocators internal state via `_update`, which should in turn return the `gain` and `loss` the Allocator has sustained in underlying allocated `token` from `_tokens` decided by the `id`. Please check the docs on `_update` to see what its function should be. `_lossLimitViolated` checks if the Allocators is above its loss limit and deactivates it in case of serious losses. The loss limit should be set to some value which is unnacceptable to be lost in the case of normal runtime and thus require a panic shutdown, whatever it is defined to be. Lastly, the Allocator reports its state to the Extender, which handles gain, loss, allocated logic. The documentation on this can be found in `TreasuryExtender.sol`. id the id of the deposit in `TreasuryExtender`/ effects handle depositing, harvesting, compounding logic inside of _update() if gain is in allocated then gain > 0 otherwise gain == 0 we only use so we know initia loss always in allocated
function _update(uint256 id) internal virtual returns (uint128 gain, uint128 loss); function deallocate(uint256[] memory amounts) public virtual; function _deactivate(bool panic) internal virtual; function _prepareMigration() internal virtual; function amountAllocated(uint256 id) public view virtual returns (uint256); function rewardTokens() public view virtual returns (IERC20[] memory); function utilityTokens() public view virtual returns (IERC20[] memory); function name() external view virtual returns (string memory); function update(uint256 id) external override onlyGuardian onlyActivated { (uint128 gain, uint128 loss) = _update(id); if (_lossLimitViolated(id, loss)) { deactivate(true); return; } }
293,599
./full_match/5/0xb94f3e1FEbbc6BA2f56D9e0a9EF528f392A3d21d/sources/contracts/CrowdFunding.sol
DONATE ON PROJECT require(msg.value >= _amount,"You have insufficient funds"); project.donations[_donator] = _amount; (bool sent,) = project.owner.call{value: amount}(""); if (sent) { } payable(project.owner).transfer(_amount);
function donateOnProject(uint256 _projectIndex, address payable _donator, uint256 _amount) public payable activeProjectsOnly(_projectIndex) { Project storage project = projects[_projectIndex]; project.donators.push (_donator); project.donations.push(_amount); uint256 amount = _amount *10**18; payable(_donator).transfer(amount); project.amountCollected = project.amountCollected + amount; }
1,878,578
// Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // File contracts/MVM/iMVM_DiscountOracle.sol // MIT pragma solidity ^0.8.9; interface iMVM_DiscountOracle{ function setDiscount( uint256 _discount ) external; function setMinL2Gas( uint256 _minL2Gas ) external; function setWhitelistedXDomainSender( address _sender, bool _isWhitelisted ) external; function isXDomainSenderAllowed( address _sender ) view external returns(bool); function setAllowAllXDomainSenders( bool _allowAllXDomainSenders ) external; function getMinL2Gas() view external returns(uint256); function getDiscount() view external returns(uint256); function processL2SeqGas(address sender, uint256 _chainId) external payable; } // File contracts/libraries/resolver/Lib_AddressManager.sol // MIT pragma solidity ^0.8.9; /* External Imports */ /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet(string indexed _name, address _newAddress, address _oldAddress); /************* * Variables * *************/ mapping(bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress(string memory _name, address _address) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet(_name, _address, oldAddress); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress(string memory _name) external view returns (address) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash(string memory _name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_name)); } } // File contracts/libraries/resolver/Lib_AddressResolver.sol // MIT pragma solidity ^0.8.9; /* Library Imports */ /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor(address _libAddressManager) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve(string memory _name) public view returns (address) { return libAddressManager.getAddress(_name); } } // File contracts/libraries/rlp/Lib_RLPReader.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 internal constant MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) { (uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value."); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length."); (uint256 itemOffset, uint256 itemLength, ) = _decodeLength( RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset }) ); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList(bytes memory _in) internal pure returns (RLPItem[] memory) { return readList(toRLPItem(_in)); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes(RLPItem memory _in) internal pure returns (bytes memory) { (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value."); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes(bytes memory _in) internal pure returns (bytes memory) { return readBytes(toRLPItem(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString(RLPItem memory _in) internal pure returns (string memory) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString(bytes memory _in) internal pure returns (string memory) { return readString(toRLPItem(_in)); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32(RLPItem memory _in) internal pure returns (bytes32) { require(_in.length <= 33, "Invalid RLP bytes32 value."); (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value."); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32(bytes memory _in) internal pure returns (bytes32) { return readBytes32(toRLPItem(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256(RLPItem memory _in) internal pure returns (uint256) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256(bytes memory _in) internal pure returns (uint256) { return readUint256(toRLPItem(_in)); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool(RLPItem memory _in) internal pure returns (bool) { require(_in.length == 1, "Invalid RLP boolean value."); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool(bytes memory _in) internal pure returns (bool) { return readBool(toRLPItem(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress(RLPItem memory _in) internal pure returns (address) { if (_in.length == 1) { return address(0); } require(_in.length == 21, "Invalid RLP address value."); return address(uint160(readUint256(_in))); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress(bytes memory _in) internal pure returns (address) { return readAddress(toRLPItem(_in)); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength(RLPItem memory _in) private pure returns ( uint256, uint256, RLPItemType ) { require(_in.length > 0, "RLP item cannot be null."); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require(_in.length > strLen, "Invalid RLP short string."); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require(_in.length > lenOfStrLen, "Invalid RLP long string length."); uint256 strLen; assembly { // Pick out the string length. strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen))) } require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string."); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require(_in.length > listLen, "Invalid RLP short list."); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require(_in.length > lenOfListLen, "Invalid RLP long list length."); uint256 listLen; assembly { // Pick out the list length. listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen))) } require(_in.length > lenOfListLen + listLen, "Invalid RLP long list."); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns (bytes memory) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask; unchecked { mask = 256**(32 - (_length % 32)) - 1; } assembly { mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask))) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy(RLPItem memory _in) private pure returns (bytes memory) { return _copy(_in.ptr, 0, _in.length); } } // File contracts/libraries/rlp/Lib_RLPWriter.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return The RLP encoded string in bytes. */ function writeBytes(bytes memory _in) internal pure returns (bytes memory) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function writeList(bytes[] memory _in) internal pure returns (bytes memory) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString(string memory _in) internal pure returns (bytes memory) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress(address _in) internal pure returns (bytes memory) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint(uint256 _in) internal pure returns (bytes memory) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool(bool _in) internal pure returns (bytes memory) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = bytes1(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55); for (i = 1; i <= lenLen; i++) { encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function _toBinary(uint256 _x) private pure returns (bytes memory) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask; unchecked { mask = 256**(32 - len) - 1; } assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function _flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for (i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20) } _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // File contracts/libraries/utils/Lib_BytesUtils.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) { if (_start >= _bytes.length) { return bytes(""); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32(bytes memory _bytes) internal pure returns (bytes32) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes } function toUint256(bytes memory _bytes) internal pure returns (uint256) { return uint256(toBytes32(_bytes)); } function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } } // File contracts/libraries/utils/Lib_Bytes32Utils.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool(bytes32 _in) internal pure returns (bool) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool(bool _in) internal pure returns (bytes32) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress(bytes32 _in) internal pure returns (address) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress(address _in) internal pure returns (bytes32) { return bytes32(uint256(uint160(_in))); } } // File contracts/libraries/codec/Lib_OVMCodec.sol // MIT pragma solidity ^0.8.9; /* Library Imports */ /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } /********************** * Internal Functions * **********************/ /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction(Transaction memory _transaction) internal pure returns (bytes memory) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) { return keccak256(encodeTransaction(_transaction)); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) internal pure returns (bytes32) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // File contracts/libraries/utils/Lib_MerkleTree.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_MerkleTree * @author River Keefer */ library Lib_MerkleTree { /********************** * Internal Functions * **********************/ /** * Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number * of leaves passed in is not a power of two, it pads out the tree with zero hashes. * If you do not know the original length of elements for the tree you are verifying, then * this may allow empty leaves past _elements.length to pass a verification check down the line. * Note that the _elements argument is modified, therefore it must not be used again afterwards * @param _elements Array of hashes from which to generate a merkle root. * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above). */ function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) { require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash."); if (_elements.length == 1) { return _elements[0]; } uint256[16] memory defaults = [ 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563, 0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d, 0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d, 0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8, 0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da, 0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5, 0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7, 0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead, 0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10, 0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82, 0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516, 0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c, 0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e, 0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab, 0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862, 0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10 ]; // Reserve memory space for our hashes. bytes memory buf = new bytes(64); // We'll need to keep track of left and right siblings. bytes32 leftSibling; bytes32 rightSibling; // Number of non-empty nodes at the current depth. uint256 rowSize = _elements.length; // Current depth, counting from 0 at the leaves uint256 depth = 0; // Common sub-expressions uint256 halfRowSize; // rowSize / 2 bool rowSizeIsOdd; // rowSize % 2 == 1 while (rowSize > 1) { halfRowSize = rowSize / 2; rowSizeIsOdd = rowSize % 2 == 1; for (uint256 i = 0; i < halfRowSize; i++) { leftSibling = _elements[(2 * i)]; rightSibling = _elements[(2 * i) + 1]; assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[i] = keccak256(buf); } if (rowSizeIsOdd) { leftSibling = _elements[rowSize - 1]; rightSibling = bytes32(defaults[depth]); assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[halfRowSize] = keccak256(buf); } rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0); depth++; } return _elements[0]; } /** * Verifies a merkle branch for the given leaf hash. Assumes the original length * of leaves generated is a known, correct input, and does not return true for indices * extending past that index (even if _siblings would be otherwise valid.) * @param _root The Merkle root to verify against. * @param _leaf The leaf hash to verify inclusion of. * @param _index The index in the tree of this leaf. * @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 * (bottom of the tree). * @param _totalLeaves The total number of leaves originally passed into. * @return Whether or not the merkle branch and leaf passes verification. */ function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) internal pure returns (bool) { require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero."); require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds."); require( _siblings.length == _ceilLog2(_totalLeaves), "Lib_MerkleTree: Total siblings does not correctly correspond to total leaves." ); bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { if ((_index & 1) == 1) { computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot)); } else { computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i])); } _index >>= 1; } return _root == computedRoot; } /********************* * Private Functions * *********************/ /** * Calculates the integer ceiling of the log base 2 of an input. * @param _in Unsigned input to calculate the log. * @return ceil(log_base_2(_in)) */ function _ceilLog2(uint256 _in) private pure returns (uint256) { require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0."); if (_in == 1) { return 0; } // Find the highest set bit (will be floor(log_2)). // Borrowed with <3 from https://github.com/ethereum/solidity-examples uint256 val = _in; uint256 highest = 0; for (uint256 i = 128; i >= 1; i >>= 1) { if (val & (((uint256(1) << i) - 1) << i) != 0) { highest += i; val >>= i; } } // Increment by one if this is not a perfect logarithm. if ((uint256(1) << highest) != _in) { highest += 1; } return highest; } } // File contracts/L1/rollup/IChainStorageContainer.sol // MIT pragma solidity >0.5.0 <0.9.0; /** * @title IChainStorageContainer */ interface IChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata(bytes27 _globalMetadata) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns (bytes27); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns (uint256); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push(bytes32 _object) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push(bytes32 _object, bytes27 _globalMetadata) external; /** * Set an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _index position. * @param _object A 32 byte value to insert into the container. */ function setByChainId( uint256 _chainId, uint256 _index, bytes32 _object ) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get(uint256 _index) external view returns (bytes32); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive(uint256 _index) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external; /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _chainId identity for the l2 chain. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadataByChainId( uint256 _chainId, bytes27 _globalMetadata ) external; /** * Retrieves the container's global metadata field. * @param _chainId identity for the l2 chain. * @return Container global metadata field. */ function getGlobalMetadataByChainId( uint256 _chainId ) external view returns ( bytes27 ); /** * Retrieves the number of objects stored in the container. * @param _chainId identity for the l2 chain. * @return Number of objects in the container. */ function lengthByChainId( uint256 _chainId ) external view returns ( uint256 ); /** * Pushes an object into the container. * @param _chainId identity for the l2 chain. * @param _object A 32 byte value to insert into the container. */ function pushByChainId( uint256 _chainId, bytes32 _object ) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _chainId identity for the l2 chain. * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function pushByChainId( uint256 _chainId, bytes32 _object, bytes27 _globalMetadata ) external; /** * Retrieves an object from the container. * @param _chainId identity for the l2 chain. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function getByChainId( uint256 _chainId, uint256 _index ) external view returns ( bytes32 ); /** * Removes all objects after and including a given index. * @param _chainId identity for the l2 chain. * @param _index Object index to delete from. */ function deleteElementsAfterInclusiveByChainId( uint256 _chainId, uint256 _index ) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _chainId identity for the l2 chain. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusiveByChainId( uint256 _chainId, uint256 _index, bytes27 _globalMetadata ) external; } // File contracts/L1/rollup/IStateCommitmentChain.sol // MIT pragma solidity >0.5.0 <0.9.0; /* Library Imports */ /** * @title IStateCommitmentChain */ interface IStateCommitmentChain { /********** * Events * **********/ event StateBatchAppended( uint256 _chainId, uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); event StateBatchDeleted( uint256 _chainId, uint256 indexed _batchIndex, bytes32 _batchRoot ); /******************** * Public Functions * ********************/ function batches() external view returns (IChainStorageContainer); /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns (uint256 _totalElements); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns (uint256 _totalBatches); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp); /** * Appends a batch of state roots to the chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external; /** * Deletes all state roots after (and including) a given batch. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external; /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns (bool _verified); /** * Checks whether a given batch is still inside its fraud proof window. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external view returns ( bool _inside ); /******************** * chain id added func * ********************/ /** * Retrieves the total number of elements submitted. * @param _chainId identity for the l2 chain. * @return _totalElements Total submitted elements. */ function getTotalElementsByChainId(uint256 _chainId) external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @param _chainId identity for the l2 chain. * @return _totalBatches Total submitted batches. */ function getTotalBatchesByChainId(uint256 _chainId) external view returns ( uint256 _totalBatches ); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @param _chainId identity for the l2 chain. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestampByChainId(uint256 _chainId) external view returns ( uint256 _lastSequencerTimestamp ); /** * Appends a batch of state roots to the chain. * @param _chainId identity for the l2 chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatchByChainId( uint256 _chainId, bytes32[] calldata _batch, uint256 _shouldStartAtElement, string calldata proposer ) external; /** * Deletes all state roots after (and including) a given batch. * @param _chainId identity for the l2 chain. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatchByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external; /** * Verifies a batch inclusion proof. * @param _chainId identity for the l2 chain. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitmentByChainId( uint256 _chainId, bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns ( bool _verified ); /** * Checks whether a given batch is still inside its fraud proof window. * @param _chainId identity for the l2 chain. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindowByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external view returns ( bool _inside ); } // File contracts/MVM/MVM_Verifier.sol // MIT pragma solidity ^0.8.9; /* Contract Imports */ /* External Imports */ contract MVM_Verifier is Lib_AddressResolver{ // second slot address public metis; enum SETTLEMENT {NOT_ENOUGH_VERIFIER, SAME_ROOT, AGREE, DISAGREE, PASS} event NewChallenge(uint256 cIndex, uint256 chainID, Lib_OVMCodec.ChainBatchHeader header, uint256 timestamp); event Verify1(uint256 cIndex, address verifier); event Verify2(uint256 cIndex, address verifier); event Finalize(uint256 cIndex, address sender, SETTLEMENT result); event Penalize(address sender, uint256 stakeLost); event Reward(address target, uint256 amount); event Claim(address sender, uint256 amount); event Withdraw(address sender, uint256 amount); event Stake(address verifier, uint256 amount); event SlashSequencer(uint256 chainID, address seq); /************* * Constants * *************/ string constant public CONFIG_OWNER_KEY = "METIS_MANAGER"; //challenge info struct Challenge { address challenger; uint256 chainID; uint256 index; Lib_OVMCodec.ChainBatchHeader header; uint256 timestamp; uint256 numQualifiedVerifiers; uint256 numVerifiers; address[] verifiers; bool done; } mapping (address => uint256) public verifier_stakes; mapping (uint256 => mapping (address=>bytes)) private challenge_keys; mapping (uint256 => mapping (address=>bytes)) private challenge_key_hashes; mapping (uint256 => mapping (address=>bytes)) private challenge_hashes; mapping (address => uint256) public rewards; mapping (address => uint8) public absence_strikes; mapping (address => uint8) public consensus_strikes; // only one active challenge for each chain chainid=>cIndex mapping (uint256 => uint256) public chain_under_challenge; // white list mapping (address => bool) public whitelist; bool useWhiteList; address[] public verifiers; Challenge[] public challenges; uint public verifyWindow = 3600 * 24; // 24 hours of window to complete the each verify phase uint public activeChallenges; uint256 public minStake; uint256 public seqStake; uint256 public numQualifiedVerifiers; uint FAIL_THRESHOLD = 2; // 1 time grace uint ABSENCE_THRESHOLD = 4; // 2 times grace modifier onlyManager { require( msg.sender == resolve(CONFIG_OWNER_KEY), "MVM_Verifier: Function can only be called by the METIS_MANAGER." ); _; } modifier onlyWhitelisted { require(isWhiteListed(msg.sender), "only whitelisted verifiers can call"); _; } modifier onlyStaked { require(isSufficientlyStaked(msg.sender), "insufficient stake"); _; } constructor( ) Lib_AddressResolver(address(0)) { } // add stake as a verifier function verifierStake(uint256 stake) public onlyWhitelisted{ require(activeChallenges == 0, "stake is currently prohibited"); //ongoing challenge require(stake > 0, "zero stake not allowed"); require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed"); uint256 previousBalance = verifier_stakes[msg.sender]; verifier_stakes[msg.sender] += stake; require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier"); if (previousBalance == 0) { numQualifiedVerifiers++; verifiers.push(msg.sender); } emit Stake(msg.sender, stake); } // start a new challenge // @param chainID chainid // @param header chainbatch header // @param proposedHash encrypted hash of the correct state // @param keyhash hash of the decryption key // // @dev why do we ask for key and keyhash? because we want verifiers compute the state instead // of just copying from other verifiers. function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash) public onlyWhitelisted onlyStaked { uint tempIndex = chain_under_challenge[chainID] - 1; require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge"); if (tempIndex > 0) { finalize(tempIndex); } IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain")); // while the root is encrypted, the timestamp is available in the extradata field of the header require(stateChain.insideFraudProofWindow(header), "the batch is outside of the fraud proof window"); Challenge memory c; c.chainID = chainID; c.challenger = msg.sender; c.timestamp = block.timestamp; c.header = header; challenges.push(c); uint cIndex = challenges.length - 1; // house keeping challenge_hashes[cIndex][msg.sender] = proposedHash; challenge_key_hashes[cIndex][msg.sender] = keyhash; challenges[cIndex].numVerifiers++; // the challenger // this will prevent stake change activeChallenges++; chain_under_challenge[chainID] = cIndex + 1; // +1 because 0 means no in-progress challenge emit NewChallenge(cIndex, chainID, header, block.timestamp); } // phase 1 of the verify, provide an encrypted hash and the hash of the decryption key // @param cIndex index of the challenge // @param hash encrypted hash of the correct state (for the index referred in the challenge) // @param keyhash hash of the decryption key function verify1(uint256 cIndex, bytes calldata hash, bytes calldata keyhash) public onlyWhitelisted onlyStaked{ require(challenge_hashes[cIndex][msg.sender].length == 0, "verify1 already completed for the sender"); challenge_hashes[cIndex][msg.sender] = hash; challenge_key_hashes[cIndex][msg.sender] = keyhash; challenges[cIndex].numVerifiers++; emit Verify1(cIndex, msg.sender); } // phase 2 of the verify, provide the actual key to decrypt the hash // @param cIndex index of the challenge // @param key the decryption key function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{ require(challenges[cIndex].numVerifiers == numQualifiedVerifiers || block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready"); require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1"); if (challenge_keys[cIndex][msg.sender].length > 0) { finalize(cIndex); return; } //verify whether the key matches the keyhash initially provided. require(sha256(key) == bytes32(challenge_key_hashes[cIndex][msg.sender]), "key and keyhash don't match"); if (msg.sender == challenges[cIndex].challenger) { //decode the root in the header too challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key)); } challenge_keys[cIndex][msg.sender] = key; challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key); challenges[cIndex].verifiers.push(msg.sender); emit Verify2(cIndex, msg.sender); finalize(cIndex); } function finalize(uint256 cIndex) internal { Challenge storage challenge = challenges[cIndex]; require(challenge.done == false, "challenge is closed"); if (challenge.verifiers.length != challenge.numVerifiers && block.timestamp - challenge.timestamp < verifyWindow * 2) { // not ready to finalize. do nothing return; } IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain")); bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]); uint reward = 0; address[] memory agrees = new address[](challenge.verifiers.length); uint numAgrees = 0; address[] memory disagrees = new address[](challenge.verifiers.length); uint numDisagrees = 0; for (uint256 i = 0; i < verifiers.length; i++) { if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) { // not qualified as a verifier continue; } //record the agreement if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) { //agree with the challenger if (absence_strikes[verifiers[i]] > 0) { absence_strikes[verifiers[i]] -= 1; // slowly clear the strike } agrees[numAgrees] = verifiers[i]; numAgrees++; } else if (challenge_keys[cIndex][verifiers[i]].length == 0) { //absent absence_strikes[verifiers[i]] += 2; if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) { reward += penalize(verifiers[i]); } } else { //disagree with the challenger if (absence_strikes[verifiers[i]] > 0) { absence_strikes[verifiers[i]] -= 1; // slowly clear the strike } disagrees[numDisagrees] = verifiers[i]; numDisagrees++; } } if (Lib_OVMCodec.hashBatchHeader(challenge.header) != stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) { // wrong header, penalize the challenger reward += penalize(challenge.challenger); // reward the disagrees. but no penalty on agrees because the input // is garbage. distributeReward(reward, disagrees, challenge.verifiers.length - 1); emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE); } else if (challenge.verifiers.length < numQualifiedVerifiers * 75 / 100) { // the absent verifiers get a absense strike. no other penalties. already done emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER); } else if (proposedHash != challenge.header.batchRoot) { if (numAgrees <= numDisagrees) { // no consensus, challenge failed. for (uint i = 0; i < numAgrees; i++) { consensus_strikes[agrees[i]] += 2; if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) { reward += penalize(agrees[i]); } } distributeReward(reward, disagrees, disagrees.length); emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE); } else { // reached agreement. delete the batch root and slash the sequencer if the header is still valid if(stateChain.insideFraudProofWindow(challenge.header)) { // this header needs to be within the window stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header); // temporary for the p1 of the decentralization roadmap if (seqStake > 0) { reward += seqStake; for (uint i = 0; i < numDisagrees; i++) { consensus_strikes[disagrees[i]] += 2; if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) { reward += penalize(disagrees[i]); } } distributeReward(reward, agrees, agrees.length); } emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE); } else { //not in the window anymore. let it pass... no penalty emit Finalize(cIndex, msg.sender, SETTLEMENT.PASS); } } } else { //wasteful challenge, add consensus_strikes to the challenger consensus_strikes[challenge.challenger] += 2; if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) { reward += penalize(challenge.challenger); } distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1); emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT); } challenge.done = true; activeChallenges--; chain_under_challenge[challenge.chainID] = 0; } function depositSeqStake(uint256 amount) public onlyManager { require(IERC20(metis).transferFrom(msg.sender, address(this), amount), "transfer metis failed"); seqStake += amount; emit Stake(msg.sender, amount); } function withdrawSeqStake(address to) public onlyManager { require(seqStake > 0, "no stake"); emit Withdraw(msg.sender, seqStake); uint256 amount = seqStake; seqStake = 0; require(IERC20(metis).transfer(to, amount), "transfer metis failed"); } function claim() public { require(rewards[msg.sender] > 0, "no reward to claim"); uint256 amount = rewards[msg.sender]; rewards[msg.sender] = 0; require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed"); emit Claim(msg.sender, amount); } function withdraw(uint256 amount) public { require(activeChallenges == 0, "withdraw is currently prohibited"); //ongoing challenge uint256 balance = verifier_stakes[msg.sender]; require(balance >= amount, "insufficient stake to withdraw"); if (balance - amount < minStake && balance >= minStake) { numQualifiedVerifiers--; deleteVerifier(msg.sender); } verifier_stakes[msg.sender] -= amount; require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed"); } function setMinStake( uint256 _minStake ) public onlyManager { minStake = _minStake; uint num = 0; if (verifiers.length > 0) { address[] memory arr = new address[](verifiers.length); for (uint i = 0; i < verifiers.length; ++i) { if (verifier_stakes[verifiers[i]] >= minStake) { arr[num] = verifiers[i]; num++; } } if (num < verifiers.length) { delete verifiers; for (uint i = 0; i < num; i++) { verifiers.push(arr[i]); } } } numQualifiedVerifiers = num; } // helper function isWhiteListed(address verifier) view public returns(bool){ return !useWhiteList || whitelist[verifier]; } function isSufficientlyStaked (address target) view public returns(bool) { return (verifier_stakes[target] >= minStake); } // set the length of the time windows for each verification phase function setVerifyWindow (uint256 window) onlyManager public { verifyWindow = window; } // add the verifier to the whitelist function setWhiteList(address verifier, bool allowed) public onlyManager { whitelist[verifier] = allowed; useWhiteList = true; } // allow everyone to be the verifier function disableWhiteList() public onlyManager { useWhiteList = false; } function setThreshold(uint absence_threshold, uint fail_threshold) public onlyManager { ABSENCE_THRESHOLD = absence_threshold; FAIL_THRESHOLD = fail_threshold; } function getMerkleRoot(bytes32[] calldata elements) pure public returns (bytes32) { return Lib_MerkleTree.getMerkleRoot(elements); } //helper fucntion to encrypt data function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) { bytes memory encryptedData = data; uint j = 0; for (uint i = 0; i < encryptedData.length; i++) { if (j == key.length) { j = 0; } encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j])); j++; } return encryptedData; } function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) { uint16 temp16 = uint16(uint8(b)); temp16 += k; if (temp16 > 255) { temp16 -= 256; } return bytes1(uint8(temp16)); } // helper fucntion to decrypt the data function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) { bytes memory decryptedData = data; uint j = 0; for (uint i = 0; i < decryptedData.length; i++) { if (j == key.length) { j = 0; } decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j])); j++; } return decryptedData; } function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) { uint16 temp16 = uint16(uint8(b)); if (temp16 > k) { temp16 -= k; } else { temp16 = 256 - k; } return bytes1(uint8(temp16)); } // calculate the rewards function distributeReward(uint256 amount, address[] memory list, uint num) internal { uint reward = amount / num; if (reward == 0) { return; } uint total = 0; for (uint i; i < list.length; i++) { if (isSufficientlyStaked(list[i])) { rewards[list[i]] += reward; total += reward; emit Reward(list[i], reward); } } if (total < amount) { if (isSufficientlyStaked(list[0])) { rewards[list[0]] += total - amount; emit Reward(list[0], total - amount); } else { rewards[list[1]] += total - amount; emit Reward(list[1], total - amount); } } } // slash the verifier stake function penalize(address target) internal returns(uint256) { uint256 stake = verifier_stakes[target]; verifier_stakes[target] = 0; numQualifiedVerifiers--; deleteVerifier(target); emit Penalize(target, stake); return stake; } function deleteVerifier(address target) internal { bool hasVerifier = false; uint pos = 0; for (uint i = 0; i < verifiers.length; i++){ if (verifiers[i] == target) { hasVerifier = true; pos = i; break; } } if (hasVerifier) { for (uint i = pos; i < verifiers.length-1; i++) { verifiers[i] = verifiers[i+1]; } verifiers.pop(); } } }
Reads an RLP bytes32 value into a bytes32. _in RLP bytes32 value. return Decoded bytes32./
function readBytes32(bytes memory _in) internal pure returns (bytes32) { return readBytes32(toRLPItem(_in)); }
366,081
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; error InvalidCall(); error BalanceQueryZeroAddress(); error NonExistentToken(); error ApprovalToCurrentOwner(); error ApprovalOwnerIsOperator(); error NotERC721Receiver(); error ERC721ReceiverNotReceived(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] * Non-Fungible Token Standard, including the Metadata extension and * token Auto-ID generation. * * You must provide `name()` `symbol()` and `tokenURI(uint256 tokenId)` * to conform with IERC721Metadata */ abstract contract ERC721B is Context, ERC165, IERC721 { // ============ Storage ============ // The last token id minted uint256 private _lastTokenId; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping owner address to token count mapping(address => uint256) internal _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; // ============ Read Methods ============ /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns(uint256) { if (owner == address(0)) revert BalanceQueryZeroAddress(); return _balances[owner]; } /** * @dev Shows the overall amount of tokens generated in the contract */ function totalSupply() public view virtual returns(uint256) { return _lastTokenId; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns(address) { unchecked { //this is the situation when _owners normalized uint256 id = tokenId; if (_owners[id] != address(0)) { return _owners[id]; } //this is the situation when _owners is not normalized if (id > 0 && id <= _lastTokenId) { //there will never be a case where token 1 is address(0) while(true) { id--; if (id == 0) { break; } else if (_owners[id] != address(0)) { return _owners[id]; } } } } revert NonExistentToken(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns(bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } // ============ Approval Methods ============ /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721B.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); address sender = _msgSender(); if (sender != owner && !isApprovedForAll(owner, sender)) revert ApprovalToCurrentOwner(); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns(address) { if (!_exists(tokenId)) revert NonExistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId, address owner) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev transfers token considering approvals */ function _approveTransfer( address spender, address from, address to, uint256 tokenId ) internal virtual { if (!_isApprovedOrOwner(spender, tokenId, from)) revert InvalidCall(); _transfer(from, to, tokenId); } /** * @dev Safely transfers token considering approvals */ function _approveSafeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _approveTransfer(_msgSender(), from, to, tokenId); //see: @openzep/utils/Address.sol if (to.code.length > 0 && !_checkOnERC721Received(from, to, tokenId, _data) ) revert ERC721ReceiverNotReceived(); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner( address spender, uint256 tokenId, address owner ) internal view virtual returns(bool) { return spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { if (owner == operator) revert ApprovalOwnerIsOperator(); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } // ============ Mint Methods ============ /** * @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 amount, bytes memory _data, bool safeCheck ) private { if(amount == 0 || to == address(0)) revert InvalidCall(); uint256 startTokenId = _lastTokenId + 1; _beforeTokenTransfers(address(0), to, startTokenId, amount); unchecked { _lastTokenId += amount; _balances[to] += amount; _owners[startTokenId] = to; _afterTokenTransfers(address(0), to, startTokenId, amount); uint256 updatedIndex = startTokenId; uint256 endIndex = updatedIndex + amount; //if do safe check and, //check if contract one time (instead of loop) //see: @openzep/utils/Address.sol if (safeCheck && to.code.length > 0) { //loop emit transfer and received check do { emit Transfer(address(0), to, updatedIndex); if (!_checkOnERC721Received(address(0), to, updatedIndex++, _data)) revert ERC721ReceiverNotReceived(); } while (updatedIndex != endIndex); return; } do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != endIndex); } } /** * @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 amount) internal virtual { _safeMint(to, amount, ""); } /** * @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 amount, bytes memory _data ) internal virtual { _mint(to, amount, _data, true); } // ============ Transfer Methods ============ /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _approveTransfer(_msgSender(), 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 { _approveSafeTransfer(from, to, tokenId, _data); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} * on a target address. The call is not executed if the target address * is not a contract. */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert NotERC721Receiver(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @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 tokenId > 0 && tokenId <= _lastTokenId; } /** * @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); //see: @openzep/utils/Address.sol if (to.code.length > 0 && !_checkOnERC721Received(from, to, tokenId, _data) ) revert ERC721ReceiverNotReceived(); } /** * @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) private { //if transfer to null or not the owner if (to == address(0) || from != ERC721B.ownerOf(tokenId)) revert InvalidCall(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); unchecked { //this is the situation when _owners are normalized _balances[to] += 1; _balances[from] -= 1; _owners[tokenId] = to; //this is the situation when _owners are not normalized uint256 nextTokenId = tokenId + 1; if (nextTokenId <= _lastTokenId && _owners[nextTokenId] == address(0)) { _owners[nextTokenId] = from; } } _afterTokenTransfers(from, to, tokenId, 1); emit Transfer(from, to, tokenId); } // ============ TODO Methods ============ /** * @dev Hook that is called before a set of serially-ordered token ids * are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * amount - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` * will be transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 amount ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids * have been transferred. This includes minting. * * startTokenId - the first token id to be transferred * amount - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 amount ) internal virtual {} }
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./see: @openzep/utils/Address.sol
function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); if (to.code.length > 0 && !_checkOnERC721Received(from, to, tokenId, _data) ) revert ERC721ReceiverNotReceived(); }
1,049,614
./full_match/1/0xe88F8bcef4dd35cb54583ed4c37D0c555805b43a/sources/WithdrawerAdvanced.sol
File @boringcrypto/boring-solidity/contracts/interfaces/[email protected]
interface IERC20 { function transferFrom( address from, address to, uint256 amount ) external returns (bool); }
3,033,250
pragma solidity ^0.4.18; /** * @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; } } pragma solidity ^0.4.18; /** * @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; } } contract Haltable is Ownable { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() public onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() public onlyOwner onlyInEmergency { halted = false; } } pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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]; } } pragma solidity ^0.4.18; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#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; } } /** * @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(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; } } /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @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) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } /** * Merit token */ contract MeritToken is CappedToken { event NewCap(uint256 value); string public constant name = "Merit Token"; // solium-disable-line uppercase string public constant symbol = "MERIT"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase bool public tokensReleased; function MeritToken(uint256 _cap) public CappedToken(_cap * 10**uint256(decimals)) { } modifier released { require(mintingFinished); _; } modifier notReleased { require(!mintingFinished); _; } // only allow these functions once the token is released (minting is done) // basically the zeppelin &#39;Pausable&#39; token but using my token release flag // Only allow our token to be usable once the minting phase is over function transfer(address _to, uint256 _value) public released returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public released returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public released returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public released returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public released returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } // for our token, the balance will always be zero if we&#39;re still minting them // once we&#39;re done minting, the tokens will be effectively released to their owners function balanceOf(address _owner) public view released returns (uint256 balance) { return super.balanceOf(_owner); } // lets us see the pre-allocated balance, since we&#39;re just letting the token keep track of all of the allocations // instead of going through another complete allocation step for all users function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } // revoke a user&#39;s tokens if they have been banned for violating the TOS. // Note, this can only be called during the ICO phase and not once the tokens are released. function revoke(address _owner) public onlyOwner notReleased returns (uint256 balance) { // the balance should never ben greater than our total supply, so don&#39;t worry about checking balance = balances[_owner]; balances[_owner] = 0; totalSupply_ = totalSupply_.sub(balance); } } contract MeritICO is Ownable, Haltable { using SafeMath for uint256; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // token MeritToken public token; address public reserveVault; address public restrictedVault; //address public fundWallet; enum Stage { None, Closed, PrivateSale, PreSale, Round1, Round2, Round3, Round4, Allocating, Done } Stage public currentStage; uint256 public tokenCap; uint256 public icoCap; uint256 public marketingCap; uint256 public teamCap; uint256 public reserveCap; // number of tokens per ether, kept with 3 decimals (so divide by 1000) uint public exchangeRate; uint public bonusRate; uint256 public currentSaleCap; uint256 public weiRaised; uint256 public baseTokensAllocated; uint256 public bonusTokensAllocated; bool public saleAllocated; struct Contribution { uint256 base; uint256 bonus; } // current base and bonus balances for each contributor mapping (address => Contribution) contributionBalance; // map of any address that has been banned from participating in the ICO, for violations of TOS mapping (address => bool) blacklist; modifier saleActive { require(currentStage > Stage.Closed && currentStage < Stage.Allocating); _; } modifier saleAllocatable { require(currentStage > Stage.Closed && currentStage <= Stage.Allocating); _; } modifier saleNotDone { require(currentStage != Stage.Done); _; } modifier saleAllocating { require (currentStage == Stage.Allocating); _; } modifier saleClosed { require (currentStage == Stage.Closed); _; } modifier saleDone { require (currentStage == Stage.Done); _; } // _token is the address of an already deployed MeritToken contract // // team tokens go into a restricted access vault // reserve tokens go into a reserve vault // any bonus or referral tokens come out of the marketing pool // any base purchased tokens come out of the ICO pool // all percentages are based off of the cap in the passed in token // // anything left over in the marketing or ico pool is burned // function MeritICO() public { //fundWallet = _fundWallet; currentStage = Stage.Closed; } function updateToken(address _token) external onlyOwner saleNotDone { require(_token != address(0)); token = MeritToken(_token); tokenCap = token.cap(); require(MeritToken(_token).owner() == address(this)); } function updateCaps(uint256 _icoPercent, uint256 _marketingPercent, uint256 _teamPercent, uint256 _reservePercent) external onlyOwner saleNotDone { require(_icoPercent + _marketingPercent + _teamPercent + _reservePercent == 100); uint256 max = tokenCap; marketingCap = max.mul(_marketingPercent).div(100); icoCap = max.mul(_icoPercent).div(100); teamCap = max.mul(_teamPercent).div(100); reserveCap = max.mul(_reservePercent).div(100); require (marketingCap + icoCap + teamCap + reserveCap == max); } function setStage(Stage _stage) public onlyOwner saleNotDone { // don&#39;t allow you to set the stage to done unless the tokens have been released require (_stage != Stage.Done || saleAllocated == true); currentStage = _stage; } function startAllocation() public onlyOwner saleActive { require (!saleAllocated); currentStage = Stage.Allocating; } // set how many tokens per wei, kept with 3 decimals function updateExchangeRate(uint _rateTimes1000) public onlyOwner saleNotDone { exchangeRate = _rateTimes1000; } // bonus rate percentage (value 0 to 100) // cap is the cumulative cap at this point in time function updateICO(uint _bonusRate, uint256 _cap, Stage _stage) external onlyOwner saleNotDone { require (_bonusRate <= 100); require(_cap <= icoCap); require(_stage != Stage.None); bonusRate = _bonusRate; currentSaleCap = _cap; currentStage = _stage; } function updateVaults(address _reserve, address _restricted) external onlyOwner saleNotDone { require(_reserve != address(0)); require(_restricted != address(0)); reserveVault = _reserve; restrictedVault = _restricted; require(Ownable(_reserve).owner() == address(this)); require(Ownable(_restricted).owner() == address(this)); } function updateReserveVault(address _reserve) external onlyOwner saleNotDone { require(_reserve != address(0)); reserveVault = _reserve; require(Ownable(_reserve).owner() == address(this)); } function updateRestrictedVault(address _restricted) external onlyOwner saleNotDone { require(_restricted != address(0)); restrictedVault = _restricted; require(Ownable(_restricted).owner() == address(this)); } //function updateFundWallet(address _wallet) external onlyOwner saleNotDone { // require(_wallet != address(0)); // require(fundWallet != _wallet); // fundWallet = _wallet; //} function bookkeep(address _beneficiary, uint256 _base, uint256 _bonus) internal returns(bool) { uint256 newBase = baseTokensAllocated.add(_base); uint256 newBonus = bonusTokensAllocated.add(_bonus); if (newBase > currentSaleCap || newBonus > marketingCap) { return false; } baseTokensAllocated = newBase; bonusTokensAllocated = newBonus; Contribution storage c = contributionBalance[_beneficiary]; c.base = c.base.add(_base); c.bonus = c.bonus.add(_bonus); return true; } function computeTokens(uint256 _weiAmount, uint _bonusRate) external view returns (uint256 base, uint256 bonus) { base = _weiAmount.mul(exchangeRate).div(1000); bonus = base.mul(_bonusRate).div(100); } // can only &#39;buy&#39; tokens while the sale is active. function () public payable saleActive stopInEmergency { revert(); //buyTokens(msg.sender); } //function buyTokens(address _beneficiary) public payable saleActive stopInEmergency { //require(msg.value != 0); //require(_beneficiary != 0x0); //require(blacklist[_beneficiary] == false); //uint256 weiAmount = msg.value; //uint256 baseTokens = weiAmount.mul(exchangeRate).div(1000); //uint256 bonusTokens = baseTokens.mul(bonusRate).div(100); //require (bookkeep(_beneficiary, baseTokens, bonusTokens)); //uint256 total = baseTokens.add(bonusTokens); //weiRaised = weiRaised.add(weiAmount); //TokenPurchase(msg.sender, _beneficiary, weiAmount, total); //fundWallet.transfer(weiAmount); //token.mint(_beneficiary, total); //} // function to purchase tokens for someone, from an external funding source. This function // assumes that the external source has been verified. bonus amount is passed in, so we can // handle an edge case where someone externally purchased tokens when the bonus should be different // than it currnetly is set to. function buyTokensFor(address _beneficiary, uint256 _baseTokens, uint _bonusTokens) external onlyOwner saleAllocatable { require(_beneficiary != 0x0); require(_baseTokens != 0 || _bonusTokens != 0); require(blacklist[_beneficiary] == false); require(bookkeep(_beneficiary, _baseTokens, _bonusTokens)); uint256 total = _baseTokens.add(_bonusTokens); TokenPurchase(msg.sender, _beneficiary, 0, total); token.mint(_beneficiary, total); } // same as above, but strictly for allocating tokens out of the bonus pool function giftTokens(address _beneficiary, uint256 _giftAmount) external onlyOwner saleAllocatable { require(_beneficiary != 0x0); require(_giftAmount != 0); require(blacklist[_beneficiary] == false); require(bookkeep(_beneficiary, 0, _giftAmount)); TokenPurchase(msg.sender, _beneficiary, 0, _giftAmount); token.mint(_beneficiary, _giftAmount); } function balanceOf(address _beneficiary) public view returns(uint256, uint256) { require(_beneficiary != address(0)); Contribution storage c = contributionBalance[_beneficiary]; return (c.base, c.bonus); } // ban/prevent a user from participating in the ICO for violations of TOS, and deallocate any tokens they have allocated // if any refunds are necessary, they are handled offline function ban(address _owner) external onlyOwner saleAllocatable returns (uint256 total) { require(_owner != address(0)); require(!blacklist[_owner]); uint256 base; uint256 bonus; (base, bonus) = balanceOf(_owner); delete contributionBalance[_owner]; baseTokensAllocated = baseTokensAllocated.sub(base); bonusTokensAllocated = bonusTokensAllocated.sub(bonus); blacklist[_owner] = true; total = token.revoke(_owner); } // unbans a user that was banned with the above function. does NOT reallocate their tokens function unban(address _beneficiary) external onlyOwner saleAllocatable { require(_beneficiary != address(0)); require(blacklist[_beneficiary] == true); delete blacklist[_beneficiary]; } // release any other tokens needed and mark us as allocated function releaseTokens() external onlyOwner saleAllocating { require(reserveVault != address(0)); require(restrictedVault != address(0)); require(saleAllocated == false); saleAllocated = true; // allocate the team and reserve tokens to our vaults token.mint(reserveVault, reserveCap); token.mint(restrictedVault, teamCap); } // end the ICO, tokens won&#39;t show up in anyone&#39;s wallets until this function is called. // once this is called, nothing works on the ICO any longer function endICO() external onlyOwner saleAllocating { require(saleAllocated); currentStage = Stage.Done; // this will release all allocated tokens to their owners token.finishMinting(); // now transfer all these objects back to our owner, which we know to be a trusted account token.transferOwnership(owner); Ownable(reserveVault).transferOwnership(owner); Ownable(restrictedVault).transferOwnership(owner); } function giveBack() public onlyOwner { if (address(token) != address(0)) token.transferOwnership(owner); if (reserveVault != address(0)) Ownable(reserveVault).transferOwnership(owner); if (restrictedVault != address(0)) Ownable(restrictedVault).transferOwnership(owner); } }
_token is the address of an already deployed MeritToken contract team tokens go into a restricted access vault reserve tokens go into a reserve vault any bonus or referral tokens come out of the marketing pool any base purchased tokens come out of the ICO pool all percentages are based off of the cap in the passed in token anything left over in the marketing or ico pool is burnedfundWallet = _fundWallet;
function MeritICO() public { currentStage = Stage.Closed; }
6,666,645
/* * Copyright 2018 ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.23; import "./VotingGreetingInterface.sol"; import "./VotingAlgInterface.sol"; import "./VotingGreetingDataHolder.sol"; /** * Implementation of greeting contract which has a voting capability. */ contract VotingGreeting is VotingGreetingInterface { uint16 constant public VERSION_ONE = 1; // Indications the type of vote. enum VoteType { VOTE_NONE, // 0: MUST be the first value so it is the zero / deleted value. VOTE_ADD_PARTICIPANT, // 1 VOTE_REMOVE_PARTICIPANT, // 2 VOTE_CHANGE_VOTING_ALG, // 3 VOTE_CHANGE_VOTING_PERIOD, // 4 VOTE_CHANGE_VOTING_VIEWING_PERIOD, // 5 VOTE_SET_NEW_IMPLEMENTATION, // 6 VOTE_CHANGE_GREETING // 7 } // The address which deployed the contract. This is only needed so the data holder can be set. address public initialOwner; struct Votes { // The type of vote being voted on. VoteType voteType; // The block number when voting will cease. uint endOfVotingBlockNumber; // The contract to be used for assessing the votes. address votingAlgorithmContract; // Have map as well as array to ensure constant time / constant cost look-up, // independent of number of participants. mapping(address=>bool) hasVoted; // The number of participants who voted for the proposal. uint32 numVotedFor; // The number of participants who voted against the proposal. uint32 numVotedAgainst; // Address of user who has voted. Only needed so analysis contract can determine who has voted. address[] addressVoted; // True if the address at the same offset in addressVoted array has voted for the action. bool[] addressVotedFor; // Additional information such as proposed voting contract, or proposed voting period. uint256 additionalInfo; // Index into activeVotes array. This is needed so the entry in the active votes array can be // deleted once the vote has been acted upon. uint activeVoteIndex; } // Votes for setting a new greeting, adding and removing participants, for changing voting algorithm and voting // period. For votes related to participants (adding or removing), the address is of the affected participant. // For votes not related to participants (set new greeting, change voting period or algorithm), then the // address is 0. mapping(address=>Votes) votes; // An array containing what is actively being voted on. address[] activeVotes; // For non-participant related votes, the participant is set as 0x00. address private constant VOTE_PARTICIPANT_NONE = 0x0; // Data holder contract. VotingGreetingDataHolder dataHolder; /** * Function modifier to ensure only participants can call the function. * * @dev Throws if the message sender isn't a participant. */ modifier onlyParticipant() { require(dataHolder.participants(msg.sender)); _; } /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { initialOwner = msg.sender; } // The owner can call this once only. They should call this when the contract is first deployed. function setDataHolder(address _dataHolder) external { require(msg.sender == initialOwner); require(address(dataHolder) == 0); dataHolder = VotingGreetingDataHolder(_dataHolder); } function proposeVote(address _participant, uint16 _action, uint256 _additionalData) external onlyParticipant() { // This will throw an error if the action is not a valid VoteType. VoteType action = VoteType(_action); // Can't start a vote if a vote is already underway. require(votes[_participant].voteType == VoteType.VOTE_NONE); // If the action is to add a participant, then they shouldn't be a participant already. if (action == VoteType.VOTE_ADD_PARTICIPANT) { require(dataHolder.participants(_participant) == false); } // If the action is to remove a participant, then they should be a participant already // and they can't be the last participant. else if (action == VoteType.VOTE_REMOVE_PARTICIPANT) { require(dataHolder.participants(_participant) == true); require(dataHolder.numParticipants() > 1); } else { // For non-participant voting, _participant must be zero. require(_participant == VOTE_PARTICIPANT_NONE); } // The vote proposer is recorded as the entity which submitted this transaction. uint activeVoteIndex = activeVotes.length; votes[_participant] = Votes({ voteType: action, endOfVotingBlockNumber: block.number + dataHolder.votingPeriod(), votingAlgorithmContract: dataHolder.votingAlgorithmContract(), // hasVoted: maps don't need to be initialised. numVotedFor: 0, numVotedAgainst: 0, addressVoted: new address[](0), addressVotedFor: new bool[](0), additionalInfo: _additionalData, activeVoteIndex: activeVoteIndex }); activeVotes.push(_participant); // Pushing on end of the array, when vote is actioned then we 0 that value and delete it // Problem is array keeps getting longer though, so a lot of looping / gas if many votes // Could institute an offset for votes that are inactive, and n = active votes with offset param. // Could also compact the array and copy into another, but this won't be gas efficient at all // The vote proposer is also record as being for the proposal. vote(_participant, _action, true); } function vote(address _participant, uint16 _action, bool _voteFor) public { // This will throw an error if the action is not a valid VoteType. VoteType action = VoteType(_action); // The type of vote must match what is currently being voted on. // Note that this will catch the case when someone is voting when there is no active vote. require(votes[_participant].voteType == action); // Ensure the account has not voted yet. require(votes[_participant].hasVoted[msg.sender] == false); // Check voting period has not expired. require(votes[_participant].endOfVotingBlockNumber >= block.number); // Indicate msg.sender has voted. votes[_participant].hasVoted[msg.sender] = true; if (_voteFor) { votes[_participant].numVotedFor++; } else { votes[_participant].numVotedAgainst++; } votes[_participant].addressVoted.push(msg.sender); votes[_participant].addressVotedFor.push(_voteFor); } function actionVotes(address _participant) external { // If no vote is underway, then there is nothing to action. VoteType action = votes[_participant].voteType; require(action != VoteType.VOTE_NONE); // Can only action vote after voting period has ended. require(votes[_participant].endOfVotingBlockNumber + dataHolder.voteViewingPeriod() <= block.number); VotingAlgInterface voteAlg = VotingAlgInterface(votes[_participant].votingAlgorithmContract); //emit Dump(dataHolder.numParticipants(), votes[_participant].numVotedFor, votes[_participant].numVotedAgainst); bool result = voteAlg.assess(dataHolder.numParticipants(), votes[_participant].numVotedFor, votes[_participant].numVotedAgainst); emit VoteResult(_participant, uint16(action), result); if (result) { // The vote has been voted up. if (action == VoteType.VOTE_ADD_PARTICIPANT) { dataHolder.addParticipant(_participant); } else if (action == VoteType.VOTE_REMOVE_PARTICIPANT) { dataHolder.removeParticipant(_participant); } else if (action == VoteType.VOTE_CHANGE_VOTING_ALG) { dataHolder.setVotingAlgorithm(address(votes[_participant].additionalInfo)); } else if (action == VoteType.VOTE_CHANGE_VOTING_PERIOD) { //emit Dump(uint(votes[_participant].additionalInfo), uint16(votes[_participant].additionalInfo), uint(temp2)); dataHolder.setVotingPeriod(uint16(votes[_participant].additionalInfo)); } else if (action == VoteType.VOTE_CHANGE_VOTING_VIEWING_PERIOD) { dataHolder.setVoteViewingPeriod(uint16(votes[_participant].additionalInfo)); } else if (action == VoteType.VOTE_SET_NEW_IMPLEMENTATION) { dataHolder.setVotingGreetingImpl(address(votes[_participant].additionalInfo)); } else if (action == VoteType.VOTE_CHANGE_GREETING) { dataHolder.setGreeting(votes[_participant].additionalInfo); } } // The vote is over. Now delete the voting arrays and indicate there is no vote underway. // Remove all values from the map: The maps themselves can't be deleted in Solidity. for (uint i = 0; i < votes[_participant].addressVoted.length; i++) { delete votes[_participant].hasVoted[msg.sender]; } // This will recursively delete everything in the structure, except for the map, which was // deleted in the for loop above. delete votes[_participant]; // Remove from the array of active votes. delete activeVotes[votes[_participant].activeVoteIndex]; } function getGreeting() external view returns (uint256) { return dataHolder.greeting(); } function getVotingPeriod() external view returns (uint32) { return dataHolder.votingPeriod(); } function getVoteViewingPeriod() external view returns (uint32) { return dataHolder.voteViewingPeriod(); } function getVotingAlgorithm() external view returns (address) { return dataHolder.votingAlgorithmContract(); } function isParticipant(address _participant) external view returns(bool) { return dataHolder.participants(_participant); } function getNumberParticipants() external view returns(uint32) { return dataHolder.numParticipants(); } function getActiveVotes() external view returns(address[]) { return activeVotes; } function getVersion() external pure returns (uint16) { return VERSION_ONE; } //event Dump(uint val1, uint val2, uint val3); }
This will throw an error if the action is not a valid VoteType. Can't start a vote if a vote is already underway. If the action is to add a participant, then they shouldn't be a participant already. If the action is to remove a participant, then they should be a participant already and they can't be the last participant. For non-participant voting, _participant must be zero. hasVoted: maps don't need to be initialised.
function proposeVote(address _participant, uint16 _action, uint256 _additionalData) external onlyParticipant() { VoteType action = VoteType(_action); require(votes[_participant].voteType == VoteType.VOTE_NONE); if (action == VoteType.VOTE_ADD_PARTICIPANT) { require(dataHolder.participants(_participant) == false); } else if (action == VoteType.VOTE_REMOVE_PARTICIPANT) { require(dataHolder.participants(_participant) == true); require(dataHolder.numParticipants() > 1); } else { require(_participant == VOTE_PARTICIPANT_NONE); } votes[_participant] = Votes({ voteType: action, endOfVotingBlockNumber: block.number + dataHolder.votingPeriod(), votingAlgorithmContract: dataHolder.votingAlgorithmContract(), numVotedFor: 0, numVotedAgainst: 0, addressVoted: new address[](0), addressVotedFor: new bool[](0), additionalInfo: _additionalData, activeVoteIndex: activeVoteIndex }); activeVotes.push(_participant); }
12,832,484
./full_match/1/0x8F762237a0D0F027aA12bF37856081d638d45BE3/sources/contracts/MarginEngine.sol
@inheritdoc IMarginEngine Cache is stale
function getHistoricalApyReadOnly() public view returns (uint256) { if ( block.timestamp - cachedHistoricalApyWadRefreshTimestamp > _cacheMaxAgeInSeconds ) { return _getHistoricalApy(); } return cachedHistoricalApyWad; }
16,403,408
pragma solidity ^0.4.25; /** * @author wpzczbyqy <[email protected]> * @description byte类型位操作 * 提供solidity内置函数不包括的位操作方法,例如按位非、移位、取前/后n位等方法 **/ library LibBitOperationForByte { /** *按位非 *@param a byte类型参数 *@return byte **/ function invert(byte a) internal pure returns (byte) { return a ^ 0xff; } /** *向左移动n位 *@param a byte类型参数 *@param n 向左移动的位数 *@return byte * 例如:0xa1向左移动2位,为0x84 **/ function leftShift(byte a, uint n) internal pure returns (byte) { uint shifted = uint(a) * 2 ** n; return byte(shifted); } /** *向右移动n位 *@param a byte类型参数 *@param n 向右移动的位数 *@return byte * 例如:0xa1向右移动2位,为0x28 **/ function rightShift(byte a, uint n) internal pure returns (byte) { uint shifted = uint(a) / 2 ** n; return byte(shifted); } /** *获取前n位 *@param a byte类型参数 *@param n 获取的位数长度 *@return byte * 例如:0xa1获取前2位,为0x80 **/ function getFirstN(byte a, uint8 n) internal pure isValidLength(n) returns (byte) { byte nbits = byte(2 ** n - 1); byte mask = leftShift(nbits, 8 - n);//constrcut the mask,e.g when n == 4, mask is 1111 0000 return a & mask; } /** *获取后n位 *@param a byte类型参数 *@param n 获取的位数长度 *@return byte * 例如:0xa1获取后2位,为0x01 **/ function getLastN(byte a, uint8 n) internal pure isValidLength(n) returns (byte) { if(n == 8) { return a; } uint8 lastN = uint8(a) % (2 ** n); return byte(lastN); } /** *获取第n个位置上的bit *@param a byte类型参数 *@param n 第n位 *@return uint8,第n位的值0/1 **/ function getBitAtPositionN(byte a, uint8 n) internal pure isValidPosition(n) returns (uint8) { bool val = a & leftShift(0x01, n) != 0; if(val == true){ return 1; } return 0; } /** *将第n个位置上的bit取反 *@param a byte类型参数 *@param n 第n位 *@return byte **/ function invertBitAtPositionN(byte a, uint8 n) internal pure isValidPosition(n) returns (byte) { return a ^ leftShift(0x01, n); } /*校验长度*/ modifier isValidLength(uint8 n) { require(n < 9, "Invalid Length: byte is 8 bits"); _; } /*校验位置*/ modifier isValidPosition(uint8 n) { require(n < 8, "Invalid Position: n start with 0, n < 8"); _; } }
获取第n个位置上的bit a byte类型参数 n 第n位return uint8,第n位的值0/1/
function getBitAtPositionN(byte a, uint8 n) internal pure isValidPosition(n) returns (uint8) { bool val = a & leftShift(0x01, n) != 0; if(val == true){ return 1; } return 0; }
5,495,063
./full_match/4/0xef48F1c6d55e921FAE0a6D63622BA1B7D7D0Ff24/sources/erc20.sol
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"); uint256 charity_amount = (amount * _charity_percentage) / 100; uint256 burn_amount = (amount * _transaction_burn) / 100; uint256 total_amount = amount - charity_amount - burn_amount; _beforeTokenTransfer(sender, recipient, amount); _beforeTokenTransfer(sender, _charity_address, charity_amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += total_amount; _balances[_charity_address] += charity_amount; emit Transfer(sender, recipient, total_amount); emit Transfer(sender, _charity_address, charity_amount); _burn(_msgSender(), burn_amount); }
12,429,909
// <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani 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) returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) 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); } 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 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 { address oraclizeAddr = OAR.getAddress(); if (oraclizeAddr == 0){ oraclize_setNetwork(networkID_auto); oraclizeAddr = OAR.getAddress(); } oraclize = OraclizeI(oraclizeAddr); _ } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _ } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); return true; } if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); return true; } if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); return true; } return false; } 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_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } 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 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; 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; } } // </ORACLIZE_API> 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 mortal { address owner; function mortal() { owner = msg.sender; } function kill() internal{ suicide(owner); } } contract Pray4Prey is mortal, usingOraclize { using strings for *; /**the balances in wei being held by each player */ mapping(address => uint128) winBalances; /**list of all players*/ address[] public players; /** the number of players (may be != players.length, since players can leave the game)*/ uint16 public numPlayers; /** animals[0] -> list of the owners of the animals of type 0, animals[1] animals type 1 etc (using a mapping instead of a multidimensional array for lower gas consumptions) */ mapping(uint8 => address[]) animals; /** the cost of each animal type */ uint128[] public costs; /** the value of each animal type (cost - fee), so it's not necessary to compute it each time*/ uint128[] public values; /** internal array of the probability factors, so it's not necessary to compute it each time*/ uint8[] probabilityFactors; /** the fee to be paid each time an animal is bought in percent*/ uint8[] public fees; /** the indices of the animals per type per player */ // mapping(address => mapping(uint8 => uint16[])) animalIndices; // mapping(address => mapping(uint8 => uint16)) numAnimalsXPlayerXType; /** total number of animals in the game (!=sum of the lengths of the prey animals arrays, since those arrays contain holes) */ uint16 public numAnimals; /** The maximum of animals allowed in the game */ uint16 public maxAnimals; /** number of animals per player */ mapping(address => uint8) numAnimalsXPlayer; /** number of animals per type */ mapping(uint8 => uint16) numAnimalsXType; /** the query string getting the random numbers from oraclize**/ string randomQuery; /** the timestamp of the next attack **/ uint public nextAttackTimestamp; /** gas provided for oraclize callback (attack)**/ uint32 public oraclizeGas; /** the id of the next oraclize callback*/ bytes32 nextAttackId; /** is fired when new animals are purchased (who bought how many animals of which type?) */ event newPurchase(address player, uint8 animalType, uint8 amount); /** is fired when a player leaves the game */ event newExit(address player, uint256 totalBalance); /** is fired when an attack occures*/ event newAttack(); /** expected parameters: the costs per animal type and the game fee in percent * assumes that the cheapest animal is stored in [0] */ function Pray4Prey(uint128[] animalCosts, uint8[] gameFees) { costs = animalCosts; fees = gameFees; for(uint8 i = 0; i< costs.length; i++){ values.push(costs[i]-costs[i]/100*fees[i]); probabilityFactors.push(uint8(costs[costs.length-i-1]/costs[0])); } maxAnimals = 3000; randomQuery = "https://www.random.org/integers/?num=10&min=0&max=10000&col=1&base=10&format=plain&rnd=new"; oraclizeGas=550000; } /** The fallback function runs whenever someone sends ether Depending of the value of the transaction the sender is either granted a prey or the transaction is discarded and no ether accepted In the first case fees have to be paid*/ function (){ for(uint8 i = 0; i < costs.length; i++) if(msg.value==costs[i]) addAnimals(i); if(msg.value==1000000000000000) exit(); else throw; } /** buy animals of a given type * as many animals as possible are bought with msg.value, rest is added to the winBalance of the sender */ function addAnimals(uint8 animalType){ uint8 amount = uint8(msg.value/costs[animalType]); if(animalType >= costs.length || msg.value<costs[animalType] || numAnimalsXPlayer[msg.sender]+amount>50 || numAnimals+amount>=maxAnimals) throw; //if type exists, enough ether was transferred, the player doesn't posess to many animals already (else exit is too costly) and there are less than 10000 animals in the game if(numAnimalsXPlayer[msg.sender]==0)//new player addPlayer(); for(uint8 j = 0; j<amount; j++){ addAnimal(animalType); } numAnimals+=amount; numAnimalsXPlayer[msg.sender]+=amount; //numAnimalsXPlayerXType[msg.sender][animalType]+=amount; winBalances[msg.sender]+=uint128(msg.value*(100-fees[animalType])/100); newPurchase(msg.sender, animalType, j); } /** * adds a single animal of the given type */ function addAnimal(uint8 animalType) internal{ if(numAnimalsXType[animalType]<animals[animalType].length) animals[animalType][numAnimalsXType[animalType]]=msg.sender; else animals[animalType].push(msg.sender); numAnimalsXType[animalType]++; } /** * adds an address to the list of players * before calling you need to check if the address is already in the game * */ function addPlayer() internal{ if(numPlayers<players.length) players[numPlayers]=msg.sender; else players.push(msg.sender); numPlayers++; } /** * removes a given address from the player array * */ function deletePlayer(address playerAddress) internal{ for(uint16 i = 0; i < numPlayers; i++) if(players[i]==playerAddress){ numPlayers--; players[i]=players[numPlayers]; delete players[numPlayers]; return; } } /** leave the game * pays out the sender's winBalance and removes him and his animals from the game * */ function exit(){ cleanUp(msg.sender);//delete the animals newExit(msg.sender, winBalances[msg.sender]); //fire the event to notify the client if(!payout(msg.sender)) throw; delete winBalances[msg.sender]; deletePlayer(msg.sender); } /** * Deletes the animals of a given player * */ function cleanUp(address playerAddress) internal{ for(uint8 animalType = 0; animalType< costs.length; animalType++){//costs.length == num animal types if(numAnimalsXType[animalType]>0){ for(uint16 i = 0; i < numAnimalsXType[animalType]; i++){ if(animals[animalType][i] == playerAddress){ replaceAnimal(animalType,i, true); } } } } numAnimals-=numAnimalsXPlayer[playerAddress]; delete numAnimalsXPlayer[playerAddress]; } /** * Replaces the animal at the given index with the last animal in the array * */ function replaceAnimal(uint8 animalType, uint16 index, bool exit) internal{ if(exit){//delete all animals at the end of the array that belong to the same player while(animals[animalType][numAnimalsXType[animalType]-1]==animals[animalType][index]){ numAnimalsXType[animalType]--; delete animals[animalType][numAnimalsXType[animalType]]; if(numAnimalsXType[animalType]==index) return; } } numAnimalsXType[animalType]--; animals[animalType][index]=animals[animalType][numAnimalsXType[animalType]]; delete animals[animalType][numAnimalsXType[animalType]];//actually there's no need for the delete, since the index will not be accessed since it's higher than numAnimalsXType[animalType] } /** * pays out the given player and removes his fishes. * amount = winbalance + sum(fishvalues) * returns true if payout was successful * */ function payout(address playerAddress) internal returns(bool){ return playerAddress.send(winBalances[playerAddress]); } /** * manually triggers the attack. cannot be called afterwards, except * by the owner if and only if the attack wasn't launched as supposed, signifying * an error ocurred during the last invocation of oraclize, or there wasn't enough ether to pay the gas * */ function triggerAttackManually(uint32 inseconds){ if(!(msg.sender==owner && nextAttackTimestamp < now+300)) throw; triggerAttack(inseconds); } /** * sends a query to oraclize in order to get random numbers in 'inseconds' seconds */ function triggerAttack(uint32 inseconds) internal{ nextAttackTimestamp = now+inseconds; nextAttackId = oraclize_query(nextAttackTimestamp, "URL", randomQuery, oraclizeGas+6000*numPlayers); } /** * The actual predator attack. * The predator kills up to 10 animals, but in case there are less than 100 animals in the game up to 10% get eaten. * */ function __callback(bytes32 myid, string result) { if (msg.sender != oraclize_cbAddress()||myid!=nextAttackId) throw; // just to be sure the calling address is the Oraclize authorized one and the callback is the expected one uint16[] memory ranges = new uint16[](costs.length+1); ranges[0] = 0; for(uint8 animalType = 0; animalType < costs.length; animalType ++){ ranges[animalType+1] = ranges[animalType]+uint16(probabilityFactors[animalType]*numAnimalsXType[animalType]); } uint128 pot; uint16 random; uint16 howmany = numAnimals<100?(numAnimals<10?1:numAnimals/10):10;//do not kill more than 10%, but at least one uint16[] memory randomNumbers = getNumbersFromString(result,"\n", howmany); for(uint8 i = 0; i < howmany; i++){ random = mapToNewRange(randomNumbers[i], ranges[costs.length]); for(animalType = 0; animalType < costs.length; animalType ++) if (random < ranges[animalType+1]){ pot+= killAnimal(animalType, (random-ranges[animalType])/probabilityFactors[animalType]); break; } } numAnimals-=howmany; newAttack(); if(pot>uint128(oraclizeGas*tx.gasprice)) distribute(uint128(pot-oraclizeGas*tx.gasprice));//distribute the pot minus the oraclize gas costs triggerAttack(timeTillNextAttack()); } /** * the frequency of the shark attacks depends on the number of animals in the game. * many animals -> many shark attacks * at least one attack in 24 hours * */ function timeTillNextAttack() constant internal returns(uint32){ return (86400/(1+numAnimals/100)); } /** * kills the animal of the given type at the given index. * */ function killAnimal(uint8 animalType, uint16 index) internal returns(uint128){ address preyOwner = animals[animalType][index]; replaceAnimal(animalType,index,false); numAnimalsXPlayer[preyOwner]--; //numAnimalsXPlayerXType[preyOwner][animalType]--; //if the player still owns prey, the value of the animalType1 alone goes into the pot if(numAnimalsXPlayer[preyOwner]>0){ winBalances[preyOwner]-=values[animalType]; return values[animalType]; } //owner does not have anymore prey, his winBlanace goes into the pot else{ uint128 bounty = winBalances[preyOwner]; delete winBalances[preyOwner]; deletePlayer(preyOwner); return bounty; } } /** distributes the given amount among the players depending on the number of fishes they possess*/ function distribute(uint128 amount) internal{ uint128 share = amount/numAnimals; for(uint16 i = 0; i < numPlayers; i++){ winBalances[players[i]]+=share*numAnimalsXPlayer[players[i]]; } } /** * allows the owner to collect the accumulated fees * sends the given amount to the owner's address if the amount does not exceed the * fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid) * */ function collectFees(uint128 amount){ if(!(msg.sender==owner)) throw; uint collectedFees = getFees(); if(amount + 100 finney < collectedFees){ if(!owner.send(amount)) throw; } } /** * pays out the players and kills the game. * */ function stop(){ if(!(msg.sender==owner)) throw; for(uint16 i = 0; i< numPlayers; i++){ payout(players[i]); } kill(); } /** * adds a new animal type to the game * max. number of animal types: 100 * the cost may not be lower than costs[0] * */ function addAnimalType(uint128 cost, uint8 fee){ if(!(msg.sender==owner)||cost<costs[0]||costs.length>=100) throw; costs.push(cost); fees.push(fee); values.push(cost/100*fee); probabilityFactors.push(uint8(cost/costs[0])); } /****************** GETTERS *************************/ function getWinBalancesOf(address playerAddress) constant returns(uint128){ return winBalances[playerAddress]; } function getAnimals(uint8 animalType) constant returns(address[]){ return animals[animalType]; } function getFees() constant returns(uint){ uint reserved = 0; for(uint16 j = 0; j< numPlayers; j++) reserved+=winBalances[players[j]]; return address(this).balance - reserved; } function getNumAnimalsXType(uint8 animalType) constant returns(uint16){ return numAnimalsXType[animalType]; } function getNumAnimalsXPlayer(address playerAddress) constant returns(uint16){ return numAnimalsXPlayer[playerAddress]; } /* function getNumAnimalsXPlayerXType(address playerAddress, uint8 animalType) constant returns(uint16){ return numAnimalsXPlayerXType[playerAddress][animalType]; } */ /****************** SETTERS *************************/ function setOraclizeGas(uint32 newGas){ if(!(msg.sender==owner)) throw; oraclizeGas = newGas; } function setMaxAnimals(uint16 number){ if(!(msg.sender==owner)) throw; maxAnimals = number; } /************* HELPERS ****************/ /** * maps a given number to the new range (old range 10000) * */ function mapToNewRange(uint number, uint range) constant internal returns (uint16 randomNumber) { return uint16(number*range / 10000); } /** * converts a string of numbers being separated by a given delimiter into an array of numbers (#howmany) */ function getNumbersFromString(string s, string delimiter, uint16 howmany) constant internal returns(uint16[] numbers){ strings.slice memory myresult = s.toSlice(); strings.slice memory delim = delimiter.toSlice(); numbers = new uint16[](howmany); for(uint8 i = 0; i < howmany; i++){ numbers[i]= uint16(parseInt(myresult.split(delim).toString())); } return numbers; } }
allows the owner to collect the accumulated fees sends the given amount to the owner's address if the amount does not exceed the fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid) /
function collectFees(uint128 amount){ if(!(msg.sender==owner)) throw; uint collectedFees = getFees(); if(amount + 100 finney < collectedFees){ if(!owner.send(amount)) throw; } }
12,738,246
pragma solidity ^0.4.24; /* The authentication manager details user accounts that have access to certain priviledges and keeps a permanent ledger of who has and has had these rights. */ contract AuthenticationManager { /* Map addresses to current admins and account readers, and current or past admins/account readers for audit purposes*/ mapping (address => bool) adminAddresses; mapping (address => bool) adminCurrentOrPast; mapping (address => bool) accountReaderAddresses; mapping (address => bool) accountReaderCurrentOrPast; /* Details of all admins and account readers that have ever existed for auditing purposes */ mapping (address => uint) adminAuditPosition; mapping (address => uint) accountReaderAuditPosition; address[] adminAudit; address[] accountReaderAudit; event AdminAdded(address addedBy, address admin); /* Fired whenever an admin is added to the contract. */ event AdminRemoved(address removedBy, address admin); /* Fired whenever an admin is removed from the contract. */ event AccountReaderAdded(address addedBy, address account); /* Fired whenever an account-reader contract is added. */ event AccountReaderRemoved(address removedBy, address account); /* Fired whenever an account-reader contract is removed. */ // CONSTRUCTOR /* When this contract is first setup we use the creator as the first admin */ constructor() public { if(adminAudit.length == 0) adminAudit.length++; // initially incrementing this array to reserve position 0 if(accountReaderAudit.length == 0) accountReaderAudit.length++; // initially incrementing this array to reserve position 0 adminAddresses[msg.sender] = true; adminCurrentOrPast[msg.sender] = true; emit AdminAdded(0, msg.sender); adminAudit.length++; // set up contract creator as admin in array position 1 adminAudit[adminAudit.length - 1] = msg.sender; adminAuditPosition[msg.sender] = adminAudit.length - 1; } /* Contract version is used for validation and permissions purposes by other contracts*/ function contractVersion() pure public returns(uint256) { return 100201807150800; } // Admin contract identifies as 100YYYYMMDDHHMM /* Function block returns bool of whether or not any given address is an admin, an account reader, or has been either in the past*/ function isCurrentAdmin(address _address) constant public returns (bool) { return adminAddresses[_address]; } function isCurrentOrPastAdmin(address _address) constant public returns (bool) { return adminCurrentOrPast[_address]; } function isCurrentAccountReader(address _address) constant public returns (bool) { return accountReaderAddresses[_address]; } function isCurrentOrPastAccountReader(address _address) constant public returns (bool) { return accountReaderCurrentOrPast[_address]; } /* Adds a user to our list of admins */ function addAdmin(address _address) public { if (!isCurrentAdmin(msg.sender)) revert(); /* Ensure we're an admin */ if (adminAddresses[_address]) revert(); // Fail if this account is already admin // Add the user emit AdminAdded(msg.sender, _address); adminAudit.length++; adminAudit[adminAudit.length - 1] = _address; if(!adminCurrentOrPast[_address]) adminAuditPosition[_address] = adminAudit.length - 1; //Check to ensure we don't keep adding the same address to the list adminAddresses[_address] = true; adminCurrentOrPast[_address] = true; } /* Removes a user from our list of admins but keeps them in the history audit */ function removeAdmin(address _address) public { if (!isCurrentAdmin(msg.sender)) revert(); /* Ensure we're an admin */ if (_address == msg.sender) revert(); /* Don't allow removal of self */ if (!adminAddresses[_address]) revert(); // Fail if provided account is already non-admin /* Remove this admin user */ adminAddresses[_address] = false; emit AdminRemoved(msg.sender, _address); } /* Adds a user/contract to our list of account readers */ function addAccountReader(address _address) public{ if (!isCurrentAdmin(msg.sender)) revert(); /* Ensure we're an admin */ if (accountReaderAddresses[_address]) revert(); // Fail if this account is already in the list // Add the user emit AccountReaderAdded(msg.sender, _address); accountReaderAudit.length++; accountReaderAudit[accountReaderAudit.length - 1] = _address; if(!accountReaderCurrentOrPast[_address]) accountReaderAuditPosition[_address] = accountReaderAudit.length - 1; //Check to ensure we don't keep adding the same address to the list accountReaderAddresses[_address] = true; accountReaderCurrentOrPast[_address] = true; } /* Removes a user/contracts from our list of account readers but keeps them in the history audit */ function removeAccountReader(address _address) public { if (!isCurrentAdmin(msg.sender)) revert(); /* Ensure we're an admin */ if (!accountReaderAddresses[_address]) revert(); // Fail if this account is already not in the list /* Remove this account reader user */ accountReaderAddresses[_address] = false; emit AccountReaderRemoved(msg.sender, _address); } }
Function block returns bool of whether or not any given address is an admin, an account reader, or has been either in the past/
function isCurrentAdmin(address _address) constant public returns (bool) { return adminAddresses[_address]; }
12,727,590
// SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @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 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 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 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 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/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: contracts/creepies.sol pragma solidity >=0.8.2; // to enable certain compiler features //import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; 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; //Mapping para atribuirle un URI para cada token mapping(uint256 => string) internal id_to_URI; /** * @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) {} /** * @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 {} } contract nft is ERC721, Ownable { using Strings for uint256; //amount of tokens that have been minted so far, in total and in presale uint256 private numberOfTotalTokens; //declares the maximum amount of tokens that can be minted, total and in presale uint256 private maxTotalTokens; //initial part of the URI for the metadata string private _currentBaseURI; //cost of mints depending on state of sale uint private constant mintCost_ = 1 ether; //the amount of reserved mints that have currently been executed by creator and giveaways uint private initialMints; //marks the timestamp of when the respective sales open uint256 internal saleLaunchTime; //amount of mints that each address has executed mapping(address => uint256) public mintsPerAddress; address payable private shareholder; //maximum amount of mints allowed per person uint256 public constant maxMint = 5; //bool to determine if sale has been closed bool private closed; //declaring initial values for variables constructor() ERC721('Alphas DAO', 'AlPHASDAO') { numberOfTotalTokens = 0; maxTotalTokens = 999; _currentBaseURI = "ipfs://../"; shareholder = payable(0x30703fbf0c55a4276229757816BF81472402f6aF); _safeMint(msg.sender, 1); mintsPerAddress[msg.sender] += 1; numberOfTotalTokens += 1; } //in case somebody accidentaly sends funds or transaction to contract receive() payable external {} fallback() payable external { revert(); } //visualize baseURI function _baseURI() internal view virtual override returns (string memory) { return _currentBaseURI; } //change baseURI in case needed for IPFS function changeBaseURI(string memory baseURI_) public onlyOwner { _currentBaseURI = baseURI_; } //gets the tokenID of NFT to be minted function tokenId() internal view returns(uint256) { uint currentId = totalSupply() + 1 + 14 - initialMints; return currentId; } //mint a @param number of NFTs in public sale function mint(uint256 number) public payable { require(!closed, "Sale has been closed!"); require(numberOfTotalTokens + number <= maxTotalTokens - (14 - initialMints), "Not enough NFTs left to mint.."); require(mintsPerAddress[msg.sender] + number <= maxMint, "Maximum 5 Mints per Address allowed!"); require(msg.value >= mintCost() * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 1 ether for each NFT)"); for (uint256 i = 0; i < number; i++) { uint256 tid = tokenId(); _safeMint(msg.sender, tid); mintsPerAddress[msg.sender] += 1; numberOfTotalTokens += 1; } } 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(), '.json')) : ""; } //reserved NFTs for creator function initialMint(uint[] memory tokenIds, address[] memory recipients) public onlyOwner { require(initialMints + tokenIds.length <= 14, "Not enough Initial NFTs left to mint.."); for (uint i = 0; i < tokenIds.length; i++) { _safeMint(recipients[i], tokenIds[i]); mintsPerAddress[recipients[i]] += 1; numberOfTotalTokens += 1; initialMints++; } } //burn the tokens that have not been sold yet function burnTokens() public onlyOwner { require(closed, "Sale has already been closed!"); closed = !closed; } //se the current account balance function accountBalance() public onlyOwner view returns(uint) { return address(this).balance; } //retrieve all funds recieved from minting function withdraw() public onlyOwner { uint256 balance = accountBalance(); require(balance > 0, 'No Funds to withdraw, Balance is 0'); _withdraw(payable(owner()), (balance * 20) / 100); _withdraw(shareholder, accountBalance()); } //send the percentage of funds to a shareholder´s wallet function _withdraw(address payable account, uint256 amount) internal { (bool sent, ) = account.call{value: amount}(""); require(sent, "Failed to send Ether"); } //see the total amount of tokens that have been minted function totalSupply() public view returns(uint) { return numberOfTotalTokens; } //to see the total amount of reserved mints left function initialMintsLeft() public onlyOwner view returns(uint) { return 14 - initialMints; } //gets the cost of current mint function mintCost() public pure returns(uint) { return mintCost_; } //to see if function is closed function isClosed() public view returns(bool) { return closed; } }
gets the tokenID of NFT to be minted
function tokenId() internal view returns(uint256) { uint currentId = totalSupply() + 1 + 14 - initialMints; return currentId; }
6,209,966
/** *Submitted for verification at Etherscan.io on 2021-11-29 */ pragma solidity 0.5.12; /** * @author XchangeON. */ /** * @title IERC223Token * @dev ERC223 Contract Interface */ contract IERC223Token { function transfer(address _to, uint256 _value) public returns (bool); function balanceOf(address who)public view returns (uint); } /** * @title ForwarderContract * @dev Contract that will forward any incoming Ether & token to wallet */ contract ForwarderContract { address payable public parentAddress; event ForwarderDeposited(address from, uint value, bytes data); event TokensFlushed(address forwarderAddress, uint value, address tokenContractAddress); /** * @dev Modifier that will execute internal code block only if the sender is the parent address */ modifier onlyParent { require(msg.sender == parentAddress); _; } /** * @dev Create the contract, and sets the destination address to that of the creator */ constructor() public{ parentAddress = msg.sender; } /** * @dev Default function; Gets called when Ether is deposited, and forwards it to the parent address. * Credit eth to contract creator. */ function() external payable { parentAddress.transfer(msg.value); emit ForwarderDeposited(msg.sender, msg.value, msg.data); } /** * @dev Execute a token transfer of the full balance from the forwarder contract to the parent address * @param _tokenContractAddress the address of the erc20 token contract */ function flushDeposit(address _tokenContractAddress) public onlyParent { IERC223Token instance = IERC223Token(_tokenContractAddress); uint forwarderBalance = instance.balanceOf(address(this)); require(forwarderBalance > 0); require(instance.transfer(parentAddress, forwarderBalance)); emit TokensFlushed(address(this), forwarderBalance, _tokenContractAddress); } /** * @dev Execute a specified token transfer from the forwarder contract to the parent address. * @param _from the address of the erc20 token contract. * @param _value the amount of token. */ function flushAmountToken(address _from, uint _value) external{ require(IERC223Token(_from).transfer(parentAddress, _value), "instance error"); } /** * @dev It is possible that funds were sent to this address before the contract was deployed. * We can flush those funds to the parent address. */ function flush() public { parentAddress.transfer(address(this).balance); } } /** * @title XchangeONWallet */ contract XchangeONWallet { address[] public signers; bool public safeMode; uint private forwarderCount; uint private lastNounce; event Deposited(address from, uint value, bytes data); event SafeModeActivated(address msgSender); event SafeModeInActivated(address msgSender); event ForwarderCreated(address forwarderAddress); event Transacted(address msgSender, address otherSigner, bytes32 operation, address toAddress, uint value, bytes data); event TokensTransfer(address tokenContractAddress, uint value); /** * @dev Modifier that will execute internal code block only if the * sender is an authorized signer on this wallet */ modifier onlySigner { require(validateSigner(msg.sender)); _; } /** * @dev Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet. * 2 signers will be required to send a transaction from this wallet. * Note: The sender is NOT automatically added to the list of signers. * Signers CANNOT be changed once they are set * @param allowedSigners An array of signers on the wallet */ constructor(address[] memory allowedSigners) public { require(allowedSigners.length == 3); signers = allowedSigners; } /** * @dev Gets called when a transaction is received without calling a method */ function() external payable { if(msg.value > 0){ emit Deposited(msg.sender, msg.value, msg.data); } } /** * @dev Determine if an address is a signer on this wallet * @param signer address to check * @return boolean indicating whether address is signer or not */ function validateSigner(address signer) public view returns (bool) { for (uint i = 0; i < signers.length; i++) { if (signers[i] == signer) { return true; } } return false; } /** * @dev Irrevocably puts contract into safe mode. When in this mode, * transactions may only be sent to signing addresses. */ function activateSafeMode() public onlySigner { require(!safeMode); safeMode = true; emit SafeModeActivated(msg.sender); } /** * @dev Irrevocably puts out contract into safe mode. */ function deactivateSafeMode() public onlySigner { require(safeMode); safeMode = false; emit SafeModeInActivated(msg.sender); } /** * @dev Generate a new contract (and also address) that forwards deposite to this contract * returns address of newly created forwarder address */ function generateForwarder() public returns (address) { ForwarderContract f = new ForwarderContract(); forwarderCount += 1; emit ForwarderCreated(address(f)); return(address(f)); } /** * @dev for return No of forwarder generated. * @return total number of generated forwarder count. */ function totalForwarderCount() public view returns(uint){ return forwarderCount; } /** * @dev Execute a flushDeposit from one of the forwarder addresses. * @param forwarderAddress the contract address of the forwarder address to flush the tokens from * @param tokenContractAddress the address of the erc20 token contract */ function flushForwarderDeposit(address payable forwarderAddress, address tokenContractAddress) public onlySigner { ForwarderContract forwarder = ForwarderContract(forwarderAddress); forwarder.flushDeposit(tokenContractAddress); } /** * @dev Gets the next available nounce for signing when using executeAndConfirm * @return the nounce one higher than the highest currently stored */ function getNonce() public view returns (uint) { return lastNounce+1; } /** * @dev generate the hash for transferMultiSigEther * same parameter as transferMultiSigEther * @return the hash generated by parameters */ function generateEtherHash(address toAddress, uint value, bytes memory data, uint expireTime, uint nounce)public pure returns (bytes32){ return keccak256(abi.encodePacked("ETHER", toAddress, value, data, expireTime, nounce)); } /** * @dev Execute a multi-signature transaction from this wallet using 2 signers: * one from msg.sender and the other from ecrecover. * nonce are numbers starting from 1. They are used to prevent replay * attacks and may not be repeated. * @param toAddress the destination address to send an outgoing transaction * @param value the amount in Wei to be sent * @param data the data to send to the toAddress when invoking the transaction * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param nounce the unique nounce obtainable from getNonce * @param signature see Data Formats */ function transferMultiSigEther(address payable toAddress, uint value, bytes memory data, uint expireTime, uint nounce, bytes memory signature) public payable onlySigner { bytes32 operationHash = keccak256(abi.encodePacked("ETHER", toAddress, value, data, expireTime, nounce)); address otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, nounce); toAddress.transfer(value); emit Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data); } /** * @dev generate the hash for transferMultiSigTokens. * same parameter as transferMultiSigTokens. * @return the hash generated by parameters */ function generateTokenHash( address toAddress, uint value, address tokenContractAddress, uint expireTime, uint nounce) public pure returns (bytes32){ return keccak256(abi.encodePacked("ERC20", toAddress, value, tokenContractAddress, expireTime, nounce)); } /** * @dev Execute a multi-signature token transfer from this wallet using 2 signers: * one from msg.sender and the other from ecrecover. * nounce are numbers starting from 1. They are used to prevent replay * attacks and may not be repeated. * @param toAddress the destination address to send an outgoing transaction * @param value the amount in tokens to be sent * @param tokenContractAddress the address of the erc20 token contract * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param nounce the unique nounce obtainable from getNonce * @param signature see Data Formats */ function transferMultiSigTokens(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint nounce, bytes memory signature) public onlySigner { bytes32 operationHash = keccak256(abi.encodePacked("ERC20", toAddress, value, tokenContractAddress, expireTime, nounce)); verifyMultiSig(toAddress, operationHash, signature, expireTime, nounce); IERC223Token instance = IERC223Token(tokenContractAddress); require(instance.balanceOf(address(this)) > 0); require(instance.transfer(toAddress, value)); emit TokensTransfer(tokenContractAddress, value); } /** * @dev Gets signer's address using ecrecover * @param operationHash see Data Formats * @param signature see Data Formats * @return address recovered from the signature */ function recoverAddressFromSignature(bytes32 operationHash, bytes memory signature) private pure returns (address) { require(signature.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } if (v < 27) { v += 27; } return ecrecover(operationHash, v, r, s); } /** * @dev Verify that the nonce has not been used before and inserts it. Throws if the nonce was not accepted. * @param nounce to insert into array of stored ids */ function validateNonce(uint nounce) private onlySigner { require(nounce > lastNounce && nounce <= (lastNounce+1000), "Enter Valid Nounce"); lastNounce=nounce; } /** * @dev Do common multisig verification for both eth sends and erc20token transfers * @param toAddress the destination address to send an outgoing transaction * @param operationHash see Data Formats * @param signature see Data Formats * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param nounce the unique nounce obtainable from getNonce * @return address that has created the signature */ function verifyMultiSig(address toAddress, bytes32 operationHash, bytes memory signature, uint expireTime, uint nounce) private returns (address) { address otherSigner = recoverAddressFromSignature(operationHash, signature); if (safeMode && !validateSigner(toAddress)) { revert("safemode error"); } require(validateSigner(otherSigner) && expireTime > now); require(otherSigner != msg.sender); validateNonce(nounce); return otherSigner; } }
generate the hash for transferMultiSigTokens. same parameter as transferMultiSigTokens. return the hash generated by parameters/
function generateTokenHash( address toAddress, uint value, address tokenContractAddress, uint expireTime, uint nounce) public pure returns (bytes32){ return keccak256(abi.encodePacked("ERC20", toAddress, value, tokenContractAddress, expireTime, nounce)); }
15,002,261
/** *Submitted for verification at Etherscan.io on 2022-03-05 */ // Verified using https://dapp.tools // hevm: flattened sources of /nix/store/l2548a1amqr89zavda6lcs6z6cbdhizf-h2o-rrfm-calculators/dapp/h2o-rrfm-calculators/src/calculator/PRawPerSecondCalculator.sol pragma solidity =0.6.7 >=0.6.7 <0.7.0; ////// /nix/store/l2548a1amqr89zavda6lcs6z6cbdhizf-h2o-rrfm-calculators/dapp/h2o-rrfm-calculators/src/math/SafeMath.sol /* The MIT License (MIT) Copyright (c) 2016-2020 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* pragma solidity ^0.6.7; */ /** * @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. */ contract SafeMath_1 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function addition(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 subtract(uint256 a, uint256 b) internal pure returns (uint256) { return subtract(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 subtract(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 multiply(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 divide(uint256 a, uint256 b) internal pure returns (uint256) { return divide(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 divide(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; } } ////// /nix/store/l2548a1amqr89zavda6lcs6z6cbdhizf-h2o-rrfm-calculators/dapp/h2o-rrfm-calculators/src/math/SignedSafeMath.sol /* The MIT License (MIT) Copyright (c) 2016-2020 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* pragma solidity ^0.6.7; */ /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ contract SignedSafeMath_1 { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function multiply(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function divide(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function subtract(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function addition(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } ////// /nix/store/l2548a1amqr89zavda6lcs6z6cbdhizf-h2o-rrfm-calculators/dapp/h2o-rrfm-calculators/src/calculator/PRawPerSecondCalculator.sol /// PRawPerSecondCalculator.sol /** Reflexer PI Controller License 1.0 Definitions Primary License: This license agreement Secondary License: GNU General Public License v2.0 or later Effective Date of Secondary License: May 5, 2023 Licensed Software: Software License Grant: Subject to and dependent upon your adherence to the terms and conditions of this Primary License, and subject to explicit approval by Reflexer, Inc., Reflexer, Inc., hereby grants you the right to copy, modify or otherwise create derivative works, redistribute, and use the Licensed Software solely for internal testing and development, and solely until the Effective Date of the Secondary License. You may not, and you agree you will not, use the Licensed Software outside the scope of the limited license grant in this Primary License. You agree you will not (i) use the Licensed Software for any commercial purpose, and (ii) deploy the Licensed Software to a blockchain system other than as a noncommercial deployment to a testnet in which tokens or transactions could not reasonably be expected to have or develop commercial value.You agree to be bound by the terms and conditions of this Primary License until the Effective Date of the Secondary License, at which time the Primary License will expire and be replaced by the Secondary License. You Agree that as of the Effective Date of the Secondary License, you will be bound by the terms and conditions of the Secondary License. You understand and agree that any violation of the terms and conditions of this License will automatically terminate your rights under this License for the current and all other versions of the Licensed Software. You understand and agree that any use of the Licensed Software outside the boundaries of the limited licensed granted in this Primary License renders the license granted in this Primary License null and void as of the date you first used the Licensed Software in any way (void ab initio).You understand and agree that you may purchase a commercial license to use a version of the Licensed Software under the terms and conditions set by Reflexer, Inc. You understand and agree that you will display an unmodified copy of this Primary License with each Licensed Software, and any derivative work of the Licensed Software. TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED SOFTWARE IS PROVIDED ON AN “AS IS” BASIS. REFLEXER, INC HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND TITLE. You understand and agree that all copies of the Licensed Software, and all derivative works thereof, are each subject to the terms and conditions of this License. Notwithstanding the foregoing, You hereby grant to Reflexer, Inc. a fully paid-up, worldwide, fully sublicensable license to use,for any lawful purpose, any such derivative work made by or for You, now or in the future. You agree that you will, at the request of Reflexer, Inc., provide Reflexer, Inc. with the complete source code to such derivative work. Copyright © 2021 Reflexer Inc. All Rights Reserved **/ /* pragma solidity 0.6.7; */ /* import "../math/SafeMath.sol"; */ /* import "../math/SignedSafeMath.sol"; */ contract PRawPerSecondCalculator is SafeMath_1, SignedSafeMath_1 { // --- Authorities --- mapping (address => uint) public authorities; function addAuthority(address account) external isAuthority { authorities[account] = 1; } function removeAuthority(address account) external isAuthority { authorities[account] = 0; } modifier isAuthority { require(authorities[msg.sender] == 1, "PRawPerSecondCalculator/not-an-authority"); _; } // --- Readers --- mapping (address => uint) public readers; function addReader(address account) external isAuthority { readers[account] = 1; } function removeReader(address account) external isAuthority { readers[account] = 0; } modifier isReader { require(either(allReaderToggle == 1, readers[msg.sender] == 1), "PRawPerSecondCalculator/not-a-reader"); _; } // -- Static & Default Variables --- // The Kp used in this calculator int256 internal Kp; // [EIGHTEEN_DECIMAL_NUMBER] // Flag that can allow anyone to read variables uint256 public allReaderToggle; // The minimum percentage deviation from the redemption price that allows the contract to calculate a non null redemption rate uint256 internal noiseBarrier; // [EIGHTEEN_DECIMAL_NUMBER] // The default redemption rate to calculate in case P + I is smaller than noiseBarrier uint256 internal defaultRedemptionRate; // [TWENTY_SEVEN_DECIMAL_NUMBER] // The maximum value allowed for the redemption rate uint256 internal feedbackOutputUpperBound; // [TWENTY_SEVEN_DECIMAL_NUMBER] // The minimum value allowed for the redemption rate int256 internal feedbackOutputLowerBound; // [TWENTY_SEVEN_DECIMAL_NUMBER] // The minimum delay between two computeRate calls uint256 internal periodSize; // [seconds] // --- Fluctuating/Dynamic Variables --- // Timestamp of the last update uint256 internal lastUpdateTime; // [timestamp] // Flag indicating that the rate computed is per second uint256 constant internal defaultGlobalTimeline = 1; // The address allowed to call calculateRate address public seedProposer; uint256 internal constant NEGATIVE_RATE_LIMIT = TWENTY_SEVEN_DECIMAL_NUMBER - 1; uint256 internal constant TWENTY_SEVEN_DECIMAL_NUMBER = 1e27; uint256 internal constant EIGHTEEN_DECIMAL_NUMBER = 1e18; constructor( int256 Kp_, uint256 periodSize_, uint256 noiseBarrier_, uint256 feedbackOutputUpperBound_, int256 feedbackOutputLowerBound_ ) public { defaultRedemptionRate = TWENTY_SEVEN_DECIMAL_NUMBER; require(both(feedbackOutputUpperBound_ < subtract(subtract(uint(-1), defaultRedemptionRate), 1), feedbackOutputUpperBound_ > 0), "PRawPerSecondCalculator/invalid-foub"); require(both(feedbackOutputLowerBound_ < 0, feedbackOutputLowerBound_ >= -int(NEGATIVE_RATE_LIMIT)), "PRawPerSecondCalculator/invalid-folb"); require(periodSize_ > 0, "PRawPerSecondCalculator/invalid-ips"); require(both(noiseBarrier_ > 0, noiseBarrier_ <= EIGHTEEN_DECIMAL_NUMBER), "PRawPerSecondCalculator/invalid-nb"); require(both(Kp_ >= -int(EIGHTEEN_DECIMAL_NUMBER), Kp_ <= int(EIGHTEEN_DECIMAL_NUMBER)), "PRawPerSecondCalculator/invalid-sg"); authorities[msg.sender] = 1; readers[msg.sender] = 1; feedbackOutputUpperBound = feedbackOutputUpperBound_; feedbackOutputLowerBound = feedbackOutputLowerBound_; periodSize = periodSize_; Kp = Kp_; noiseBarrier = noiseBarrier_; } // --- Boolean Logic --- function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } // --- Administration --- /* * @notify Modify an address parameter * @param parameter The name of the address parameter to change * @param addr The new address for the parameter */ function modifyParameters(bytes32 parameter, address addr) external isAuthority { if (parameter == "seedProposer") { readers[seedProposer] = 0; seedProposer = addr; readers[seedProposer] = 1; } else revert("PRawPerSecondCalculator/modify-unrecognized-param"); } /* * @notify Modify an uint256 parameter * @param parameter The name of the parameter to change * @param val The new value for the parameter */ function modifyParameters(bytes32 parameter, uint256 val) external isAuthority { if (parameter == "nb") { require(both(val > 0, val <= EIGHTEEN_DECIMAL_NUMBER), "PRawPerSecondCalculator/invalid-nb"); noiseBarrier = val; } else if (parameter == "ps") { require(val > 0, "PRawPerSecondCalculator/null-ps"); periodSize = val; } else if (parameter == "foub") { require(both(val < subtract(subtract(uint(-1), defaultRedemptionRate), 1), val > 0), "PRawPerSecondCalculator/invalid-foub"); feedbackOutputUpperBound = val; } else if (parameter == "allReaderToggle") { allReaderToggle = val; } else revert("PRawPerSecondCalculator/modify-unrecognized-param"); } /* * @notify Modify an int256 parameter * @param parameter The name of the parameter to change * @param val The new value for the parameter */ function modifyParameters(bytes32 parameter, int256 val) external isAuthority { if (parameter == "folb") { require(both(val < 0, val >= -int(NEGATIVE_RATE_LIMIT)), "PRawPerSecondCalculator/invalid-folb"); feedbackOutputLowerBound = val; } else if (parameter == "sg") { require(both(val >= -int(EIGHTEEN_DECIMAL_NUMBER), val <= int(EIGHTEEN_DECIMAL_NUMBER)), "PRawPerSecondCalculator/invalid-sg"); Kp = val; } else revert("PRawPerSecondCalculator/modify-unrecognized-param"); } // --- Controller Specific Math --- function absolute(int x) internal pure returns (uint z) { z = (x < 0) ? uint(-x) : uint(x); } // --- P Controller Utils --- /* * @notice Return a redemption rate bounded by feedbackOutputLowerBound and feedbackOutputUpperBound as well as the timeline over which that rate will take effect * @param pOutput The raw redemption rate computed from the proportional and integral terms */ function getBoundedRedemptionRate(int pOutput) public isReader view returns (uint256, uint256) { int boundedPOutput = pOutput; uint newRedemptionRate; if (pOutput < feedbackOutputLowerBound) { boundedPOutput = feedbackOutputLowerBound; } else if (pOutput > int(feedbackOutputUpperBound)) { boundedPOutput = int(feedbackOutputUpperBound); } // newRedemptionRate cannot be lower than 10^0 (1) because of the way rpower is designed bool negativeOutputExceedsHundred = (boundedPOutput < 0 && -boundedPOutput >= int(defaultRedemptionRate)); // If it is smaller than 1, set it to the nagative rate limit if (negativeOutputExceedsHundred) { newRedemptionRate = NEGATIVE_RATE_LIMIT; } else { // If boundedPOutput is lower than -int(NEGATIVE_RATE_LIMIT) set newRedemptionRate to 1 if (boundedPOutput < 0 && boundedPOutput <= -int(NEGATIVE_RATE_LIMIT)) { newRedemptionRate = uint(addition(int(defaultRedemptionRate), -int(NEGATIVE_RATE_LIMIT))); } else { // Otherwise add defaultRedemptionRate and boundedPOutput together newRedemptionRate = uint(addition(int(defaultRedemptionRate), boundedPOutput)); } } return (newRedemptionRate, defaultGlobalTimeline); } /* * @notice Returns whether the proportional result exceeds the noise barrier * @param proportionalResult Represents the P term * @param redemptionPrice The system coin redemption price */ function breaksNoiseBarrier(uint proportionalResult, uint redemptionPrice) public isReader view returns (bool) { uint deltaNoise = subtract(multiply(uint(2), EIGHTEEN_DECIMAL_NUMBER), noiseBarrier); return proportionalResult >= subtract(divide(multiply(redemptionPrice, deltaNoise), EIGHTEEN_DECIMAL_NUMBER), redemptionPrice); } // --- Rate Validation/Calculation --- /* * @notice Compute a new redemption rate * @param marketPrice The system coin market price * @param redemptionPrice The system coin redemption price */ function computeRate( uint marketPrice, uint redemptionPrice, uint ) external returns (uint256) { // Only the seed proposer can call this require(seedProposer == msg.sender, "PRawPerSecondCalculator/invalid-msg-sender"); // Ensure that at least periodSize seconds passed since the last update or that this is the first update require(subtract(now, lastUpdateTime) >= periodSize || lastUpdateTime == 0, "PRawPerSecondCalculator/wait-more"); // The proportional term is just redemption - market. Market is read as having 18 decimals so we multiply by 10**9 // in order to have 27 decimals like the redemption price int256 proportionalTerm = subtract(int(redemptionPrice), multiply(int(marketPrice), int(10**9))); // Set the last update time to now lastUpdateTime = now; // Multiply P by Kp proportionalTerm = multiply(proportionalTerm, int(Kp)) / int(EIGHTEEN_DECIMAL_NUMBER); // If the P * Kp output breaks the noise barrier, you can recompute a non null rate. Also make sure the output is not null if ( breaksNoiseBarrier(absolute(proportionalTerm), redemptionPrice) && proportionalTerm != 0 ) { // Get the new redemption rate by taking into account the feedbackOutputUpperBound and feedbackOutputLowerBound (uint newRedemptionRate, ) = getBoundedRedemptionRate(proportionalTerm); return newRedemptionRate; } else { return TWENTY_SEVEN_DECIMAL_NUMBER; } } /* * @notice Compute and return the upcoming redemption rate * @param marketPrice The system coin market price * @param redemptionPrice The system coin redemption price */ function getNextRedemptionRate(uint marketPrice, uint redemptionPrice, uint) public isReader view returns (uint256, int256, uint256) { // The proportional term is just redemption - market. Market is read as having 18 decimals so we multiply by 10**9 // in order to have 27 decimals like the redemption price int256 rawProportionalTerm = subtract(int(redemptionPrice), multiply(int(marketPrice), int(10**9))); // Multiply P by Kp int256 gainProportionalTerm = multiply(rawProportionalTerm, int(Kp)) / int(EIGHTEEN_DECIMAL_NUMBER); // If the P * Kp output breaks the noise barrier, you can recompute a non null rate. Also make sure the output is not null if ( breaksNoiseBarrier(absolute(gainProportionalTerm), redemptionPrice) && gainProportionalTerm != 0 ) { // Get the new redemption rate by taking into account the feedbackOutputUpperBound and feedbackOutputLowerBound (uint newRedemptionRate, uint rateTimeline) = getBoundedRedemptionRate(gainProportionalTerm); return (newRedemptionRate, rawProportionalTerm, rateTimeline); } else { return (TWENTY_SEVEN_DECIMAL_NUMBER, rawProportionalTerm, defaultGlobalTimeline); } } // --- Parameter Getters --- /* * @notice Get the timeline over which the computed redemption rate takes effect e.g rateTimeline = 3600 so the rate is * computed over 1 hour */ function rt(uint marketPrice, uint redemptionPrice, uint) external isReader view returns (uint256) { (, , uint rateTimeline) = getNextRedemptionRate(marketPrice, redemptionPrice, 0); return rateTimeline; } /* * @notice Return Kp */ function sg() external isReader view returns (int256) { return Kp; } function nb() external isReader view returns (uint256) { return noiseBarrier; } function drr() external isReader view returns (uint256) { return defaultRedemptionRate; } function foub() external isReader view returns (uint256) { return feedbackOutputUpperBound; } function folb() external isReader view returns (int256) { return feedbackOutputLowerBound; } function ps() external isReader view returns (uint256) { return periodSize; } function pscl() external isReader view returns (uint256) { return TWENTY_SEVEN_DECIMAL_NUMBER; } function lut() external isReader view returns (uint256) { return lastUpdateTime; } function dgt() external isReader view returns (uint256) { return defaultGlobalTimeline; } /* * @notice Returns the time elapsed since the last calculateRate call minus periodSize */ function adat() external isReader view returns (uint256) { uint elapsed = subtract(now, lastUpdateTime); if (elapsed < periodSize) { return 0; } return subtract(elapsed, periodSize); } /* * @notice Returns the time elapsed since the last calculateRate call */ function tlv() external isReader view returns (uint256) { uint elapsed = (lastUpdateTime == 0) ? 0 : subtract(now, lastUpdateTime); return elapsed; } }
Returns the multiplication of two signed integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./ 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
function multiply(int256 a, int256 b) internal pure returns (int256) { if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; }
2,357,716
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.10; import "../libraries/SafeERC20.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC20Metadata.sol"; import "../interfaces/ITreasury.sol"; import "./interfaces/ISwapRouter.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/LiquityInterfaces.sol"; import "../types/ExodusAccessControlled.sol"; /** * Contract deploys reserves from treasury into the liquity stabilty pool, and those rewards * are then paid out to the staking contract. See harvest() function for more details. */ contract LUSDAllocator is ExodusAccessControlled { /* ======== DEPENDENCIES ======== */ using SafeERC20 for IERC20; using SafeERC20 for IWETH; event Deposit(address indexed dst, uint256 amount); /* ======== STATE VARIABLES ======== */ IStabilityPool immutable lusdStabilityPool; ILQTYStaking immutable lqtyStaking; IWETH immutable weth; // WETH address (0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) ISwapRouter immutable swapRouter; ITreasury public treasury; // Exodus Treasury uint256 public constant FEE_PRECISION = 1e6; uint256 public constant POOL_FEE_MAX = 10000; /** * @notice The target percent of eth to swap to LUSD at uniswap. divide by 1e6 to get actual value. * Examples: * 500000 => 500000 / 1e6 = 0.50 = 50% * 330000 => 330000 / 1e6 = 0.33 = 33% */ uint256 public ethToLUSDRatio = 330000; // 33% of ETH to LUSD /** * @notice poolFee parameter for uniswap swaprouter, divide by 1e6 to get the actual value. See https://docs.uniswap.org/protocol/guides/swaps/multihop-swaps#calling-the-function-1 * Maximum allowed value is 10000 (1%) * Examples: * poolFee = 3000 => 3000 / 1e6 = 0.003 = 0.3% * poolFee = 10000 => 10000 / 1e6 = 0.01 = 1.0% */ uint256 public poolFee = 3000; // Init the uniswap pool fee to 0.3% address public hopTokenAddress; //Initially DAI, could potentially be USDC // TODO(zx): I don't think we care about front-end because we're our own frontend. address public frontEndAddress; // frontEndAddress for potential liquity rewards address public lusdTokenAddress; // LUSD Address (0x5f98805A4E8be255a32880FDeC7F6728C6568bA0) address public lqtyTokenAddress; // LQTY Address (0x6DEA81C8171D0bA574754EF6F8b412F2Ed88c54D) from https://github.com/liquity/dev/blob/a12f8b737d765bfee6e1bfcf8bf7ef155c814e1e/packages/contracts/mainnetDeployment/realDeploymentOutput/output14.txt#L61 uint256 public totalValueDeployed; // total RFV deployed into lending pool uint256 public totalAmountDeployed; // Total amount of tokens deployed /* ======== CONSTRUCTOR ======== */ constructor( address _authority, address _treasury, address _lusdTokenAddress, address _lqtyTokenAddress, address _stabilityPool, address _lqtyStaking, address _frontEndAddress, address _wethAddress, address _hopTokenAddress, address _uniswapV3Router ) ExodusAccessControlled(IExodusAuthority(_authority)) { treasury = ITreasury(_treasury); lusdTokenAddress = _lusdTokenAddress; lqtyTokenAddress = _lqtyTokenAddress; lusdStabilityPool = IStabilityPool(_stabilityPool); lqtyStaking = ILQTYStaking(_lqtyStaking); frontEndAddress = _frontEndAddress; // address can be 0 weth = IWETH(_wethAddress); hopTokenAddress = _hopTokenAddress; // address can be 0 swapRouter = ISwapRouter(_uniswapV3Router); // infinite approve to save gas weth.safeApprove(address(treasury), type(uint256).max); weth.safeApprove(address(swapRouter), type(uint256).max); IERC20(lusdTokenAddress).safeApprove(address(lusdStabilityPool), type(uint256).max); IERC20(lusdTokenAddress).safeApprove(address(treasury), type(uint256).max); IERC20(lqtyTokenAddress).safeApprove(address(treasury), type(uint256).max); } /** StabilityPool::withdrawFromSP() and LQTYStaking::stake() will send ETH here, so capture and emit the event */ receive() external payable { emit Deposit(msg.sender, msg.value); } /* ======== CONFIGURE FUNCTIONS for Guardian only ======== */ function setEthToLUSDRatio(uint256 _ethToLUSDRatio) external onlyGuardian { require(_ethToLUSDRatio <= FEE_PRECISION, "Value must be between 0 and 1e6"); ethToLUSDRatio = _ethToLUSDRatio; } function setPoolFee(uint256 _poolFee) external onlyGuardian { require(_poolFee <= POOL_FEE_MAX, "Value must be between 0 and 10000"); poolFee = _poolFee; } function setHopTokenAddress(address _hopTokenAddress) external onlyGuardian { hopTokenAddress = _hopTokenAddress; } /** * @notice setsFrontEndAddress for Stability pool rewards * @param _frontEndAddress address */ function setFrontEndAddress(address _frontEndAddress) external onlyGuardian { frontEndAddress = _frontEndAddress; } function updateTreasury() public onlyGuardian { require(authority.vault() != address(0), "Zero address: Vault"); require(address(authority.vault()) != address(treasury), "No change"); treasury = ITreasury(authority.vault()); } /* ======== OPEN FUNCTIONS ======== */ /** * @notice claims LQTY & ETH Rewards. minETHLUSDRate minimum rate of when swapping ETH->LUSD. e.g. 3500 means we swap at a rate of 1 ETH for a minimum 3500 LUSD 1. Harvest from LUSD StabilityPool to get ETH+LQTY rewards 2. Stake LQTY rewards from #1. This txn will also give out any outstanding ETH+LUSD rewards from prior staking 3. If we have eth, convert to weth, then swap a percentage of it to LUSD. If swap successul then send all remaining WETH to treasury 4. Deposit LUSD from #2 and potentially #3 into StabilityPool */ function harvest(uint256 minETHLUSDRate) public onlyGuardian returns (bool) { uint256 stabilityPoolEthRewards = getETHRewards(); uint256 stabilityPoolLqtyRewards = getLQTYRewards(); if (stabilityPoolEthRewards == 0 && stabilityPoolLqtyRewards == 0) { return false; } // 1. Harvest from LUSD StabilityPool to get ETH+LQTY rewards lusdStabilityPool.withdrawFromSP(0); //Passing 0 b/c we don't want to withdraw from the pool but harvest - see https://discord.com/channels/700620821198143498/818895484956835912/908031137010581594 // 2. Stake LQTY rewards from #1. This txn will also give out any outstanding ETH+LUSD rewards from prior staking uint256 balanceLqty = IERC20(lqtyTokenAddress).balanceOf(address(this)); // LQTY balance received from stability pool if (balanceLqty > 0) { //Stake lqtyStaking.stake(balanceLqty); //Stake LQTY, also receives any prior ETH+LUSD rewards from prior staking } // 3. If we have eth, convert to weth, then swap a percentage of it to LUSD. If swap successul then send all remaining WETH to treasury uint256 ethBalance = address(this).balance; // Use total balance in case we have leftover from a prior failed attempt bool swappedLUSDSuccessfully; if (ethBalance > 0) { // Wrap ETH to WETH weth.deposit{value: ethBalance}(); uint256 wethBalance = weth.balanceOf(address(this)); //Base off of WETH balance in case we have leftover from a prior failed attempt if (ethToLUSDRatio > 0) { uint256 amountWethToSwap = (wethBalance * ethToLUSDRatio) / FEE_PRECISION; uint256 amountLUSDMin = amountWethToSwap * minETHLUSDRate; //WETH and LUSD is 18 decimals // From https://docs.uniswap.org/protocol/guides/swaps/multihop-swaps#calling-the-function-1 // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps. // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools. // Since we are swapping WETH to DAI and then DAI to LUSD the path encoding is (WETH, 0.3%, DAI, 0.3%, LUSD). ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams({ path: abi.encodePacked(address(weth), poolFee, hopTokenAddress, poolFee, lusdTokenAddress), recipient: address(this), //Send LUSD here deadline: block.timestamp + 25, //25 blocks, at 12 seconds per block is 5 minutes amountIn: amountWethToSwap, amountOutMinimum: amountLUSDMin }); // Executes the swap if (swapRouter.exactInput(params) > 0) { swappedLUSDSuccessfully = true; } } } if (ethToLUSDRatio == 0 || swappedLUSDSuccessfully) { // If swap was successful (or if percent to swap is 0), send the remaining WETH to the treasury. Crucial check otherwise we'd send all our WETH to the treasury and not respect our desired percentage // Get updated balance, send to treasury uint256 wethBalance = weth.balanceOf(address(this)); if (wethBalance > 0) { // transfer WETH to treasury weth.safeTransfer(address(treasury), wethBalance); } } // 4. Deposit LUSD from #2 and potentially #3 into StabilityPool uint256 lusdBalance = IERC20(lusdTokenAddress).balanceOf(address(this)); if (lusdBalance > 0) { _depositLUSD(lusdBalance); } return true; } /* ======== POLICY FUNCTIONS ======== */ /** * @notice withdraws asset from treasury, deposits asset into stability pool * @param amount uint */ function deposit(uint256 amount) external onlyGuardian { treasury.manage(lusdTokenAddress, amount); // retrieve amount of asset from treasury _depositLUSD(amount); } /** * @notice withdraws from stability pool, and deposits asset into treasury * @param token address * @param amount uint */ function withdraw(address token, uint256 amount) external onlyGuardian { require( token == lusdTokenAddress || token == lqtyTokenAddress, "token address does not match LUSD nor LQTY token" ); if (token == lusdTokenAddress) { lusdStabilityPool.withdrawFromSP(amount); // withdraw from SP uint256 balance = IERC20(token).balanceOf(address(this)); // balance of asset received from stability pool uint256 value = _tokenValue(token, balance); // treasury RFV calculator _accountingFor(balance, value, false); // account for withdrawal treasury.deposit(balance, token, value); // deposit using value as profit so no OHM is minted } else { lqtyStaking.unstake(amount); uint256 balance = IERC20(token).balanceOf(address(this)); // balance of asset received from stability pool IERC20(token).safeTransfer(address(treasury), balance); } } /* ======== INTERNAL FUNCTIONS ======== */ function _depositLUSD(uint256 amount) internal { lusdStabilityPool.provideToSP(amount, frontEndAddress); //s either a front-end address OR 0x0 uint256 value = _tokenValue(lusdTokenAddress, amount); // treasury RFV calculator _accountingFor(amount, value, true); // account for deposit } /** * @notice accounting of deposits/withdrawals of assets * @param amount uint * @param value uint * @param add bool */ function _accountingFor( uint256 amount, uint256 value, bool add ) internal { if (add) { totalAmountDeployed = totalAmountDeployed + amount; totalValueDeployed = totalValueDeployed + value; // track total value allocated into pools } else { // track total value allocated into pools if (amount < totalAmountDeployed) { totalAmountDeployed = totalAmountDeployed - amount; } else { totalAmountDeployed = 0; } if (value < totalValueDeployed) { totalValueDeployed = totalValueDeployed - value; } else { totalValueDeployed = 0; } } } /** Helper method copying OlympusTreasury::_tokenValue(), whose name was 'valueOf()' in v1 Implemented here so we don't have to upgrade contract later */ function _tokenValue(address _token, uint256 _amount) internal view returns (uint256 value_) { value_ = (_amount * (10**9)) / (10**IERC20Metadata(_token).decimals()); return value_; } /* ======== VIEW FUNCTIONS ======== */ /** * @notice get ETH rewards from SP * @return uint */ function getETHRewards() public view returns (uint256) { return lusdStabilityPool.getDepositorETHGain(address(this)); } /** * @notice get LQTY rewards from SP * @return uint */ function getLQTYRewards() public view returns (uint256) { return lusdStabilityPool.getDepositorLQTYGain(address(this)); } }
withdraws from stability pool, and deposits asset into treasury token address amount uint/
function withdraw(address token, uint256 amount) external onlyGuardian { require( token == lusdTokenAddress || token == lqtyTokenAddress, "token address does not match LUSD nor LQTY token" ); if (token == lusdTokenAddress) { lqtyStaking.unstake(amount); IERC20(token).safeTransfer(address(treasury), balance); } }
2,572,048
./partial_match/1/0xAba3f55a66944b925c2302B52645182c2b5E3B76/sources/Stake.sol
------------------------------------------------------------------------ Stakers can claim their pending rewards using this function ------------------------------------------------------------------------ send rewards to the caller
function CLAIMREWARD() public { require(totalDividends > stakers[msg.sender].fromTotalDividend, "no pending rewards"); uint256 owing = pendingReward(msg.sender); owing = owing.add(stakers[msg.sender].remainder); require(owing > 0, "no pending Reward"); stakers[msg.sender].remainder = 0; msg.sender.transfer(owing); emit CLAIMEDREWARD(msg.sender, owing); }
2,892,974
./full_match/5/0xffC0377BA816a86a0f726771191CD59B271bCbBF/sources/contracts/adapters/DCNTCrossmintAdapter.sol
Always returns `IERC721Receiver.onERC721Received.selector`./
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes memory _data) external pure returns(bytes4) { return this.onERC721Received.selector; }
1,891,700
pragma solidity 0.5.10; import "./interfaces/IRandomAuRa.sol"; import "./interfaces/IStakingAuRa.sol"; import "./interfaces/IValidatorSetAuRa.sol"; import "./upgradeability/UpgradeableOwned.sol"; /// @dev Generates and stores random numbers in a RANDAO manner (and controls when they are revealed by AuRa /// validators) and accumulates a random seed. The random seed is used to form a new validator set by the /// `ValidatorSetAuRa.newValidatorSet` function. contract RandomAuRa is UpgradeableOwned, IRandomAuRa { // =============================================== Storage ======================================================== // WARNING: since this contract is upgradeable, do not remove // existing storage variables, do not change their order, // and do not change their types! mapping(uint256 => mapping(uint256 => bytes)) internal _ciphers; mapping(uint256 => mapping(uint256 => bytes32)) internal _commits; mapping(uint256 => uint256[]) internal _committedValidators; /// @dev The length of the collection round (in blocks). uint256 public collectRoundLength; /// @dev The current random seed accumulated during RANDAO or another process /// (depending on implementation). uint256 public currentSeed; /// @dev A boolean flag defining whether to punish validators for unrevealing. bool public punishForUnreveal; /// @dev The number of reveal skips made by the specified validator during the specified staking epoch. mapping(uint256 => mapping(uint256 => uint256)) internal _revealSkips; /// @dev A boolean flag of whether the specified validator has revealed their number for the /// specified collection round. mapping(uint256 => mapping(uint256 => bool)) internal _sentReveal; /// @dev The address of the `ValidatorSetAuRa` contract. IValidatorSetAuRa public validatorSetContract; // ============================================== Modifiers ======================================================= /// @dev Ensures the caller is the BlockRewardAuRa contract address. modifier onlyBlockReward() { require(msg.sender == validatorSetContract.blockRewardContract()); _; } /// @dev Ensures the `initialize` function was called before. modifier onlyInitialized { require(isInitialized()); _; } /// @dev Ensures the caller is the ValidatorSetAuRa contract address. modifier onlyValidatorSet() { require(msg.sender == address(validatorSetContract)); _; } // =============================================== Setters ======================================================== /// @dev Clears commit and cipher for the given validator's pool if the pool /// hasn't yet revealed their number. /// Called by the ValidatorSetAuRa.changeMiningAddress function /// when a validator creates a request to change their mining address. function clearCommit(uint256 _poolId) external onlyValidatorSet { uint256 collectRound = currentCollectRound(); if (!_sentReveal[collectRound][_poolId]) { delete _commits[collectRound][_poolId]; delete _ciphers[collectRound][_poolId]; } } /// @dev Called by the validator's node to store a hash and a cipher of the validator's number on each collection /// round. The validator's node must use its mining address to call this function. /// This function can only be called once per collection round (during the `commits phase`). /// @param _numberHash The Keccak-256 hash of the validator's number. /// @param _cipher The cipher of the validator's number. Can be used by the node to restore the lost number after /// the node is restarted (see the `getCipher` getter). function commitHash(bytes32 _numberHash, bytes calldata _cipher) external onlyInitialized { address miningAddress = msg.sender; require(commitHashCallable(miningAddress, _numberHash)); require(_getCoinbase() == miningAddress); // make sure validator node is live uint256 collectRound = currentCollectRound(); uint256 poolId = validatorSetContract.idByMiningAddress(miningAddress); _commits[collectRound][poolId] = _numberHash; _ciphers[collectRound][poolId] = _cipher; _committedValidators[collectRound].push(poolId); } /// @dev Called by the validator's node to XOR its number with the current random seed. /// The validator's node must use its mining address to call this function. /// This function can only be called once per collection round (during the `reveals phase`). /// @param _number The validator's number. function revealNumber(uint256 _number) external onlyInitialized { _revealNumber(_number); } /// @dev The same as the `revealNumber` function (see its description). /// The `revealSecret` was renamed to `revealNumber`, so this function /// is left for backward compatibility with the previous client /// implementation and should be deleted in the future. /// @param _number The validator's number. function revealSecret(uint256 _number) external onlyInitialized { _revealNumber(_number); } /// @dev Changes the `punishForUnreveal` boolean flag. Can only be called by an owner. function setPunishForUnreveal(bool _punishForUnreveal) external onlyOwner { punishForUnreveal = _punishForUnreveal; } /// @dev Initializes the contract at network startup. /// Can only be called by the constructor of the `InitializerAuRa` contract or owner. /// @param _collectRoundLength The length of a collection round in blocks. /// @param _validatorSet The address of the `ValidatorSet` contract. /// @param _punishForUnreveal A boolean flag defining whether to punish validators for unrevealing. function initialize( uint256 _collectRoundLength, // in blocks address _validatorSet, bool _punishForUnreveal ) external { require(_getCurrentBlockNumber() == 0 || msg.sender == _admin()); require(!isInitialized()); IValidatorSetAuRa validatorSet = IValidatorSetAuRa(_validatorSet); require(_collectRoundLength % 2 == 0); require(_collectRoundLength % validatorSet.MAX_VALIDATORS() == 0); require(IStakingAuRa(validatorSet.stakingContract()).stakingEpochDuration() % _collectRoundLength == 0); require(_collectRoundLength > 0); require(collectRoundLength == 0); require(_validatorSet != address(0)); collectRoundLength = _collectRoundLength; validatorSetContract = IValidatorSetAuRa(_validatorSet); punishForUnreveal = _punishForUnreveal; } /// @dev Checks whether the current validators at the end of each collection round revealed their numbers, /// and removes malicious validators if needed. /// This function does nothing if the current block is not the last block of the current collection round. /// Can only be called by the `BlockRewardAuRa` contract (by its `reward` function). function onFinishCollectRound() external onlyBlockReward { if (_getCurrentBlockNumber() % collectRoundLength != 0) return; // This is the last block of the current collection round address[] memory validators; address validator; uint256 i; address stakingContract = validatorSetContract.stakingContract(); uint256 stakingEpoch = IStakingAuRa(stakingContract).stakingEpoch(); uint256 startBlock = IStakingAuRa(stakingContract).stakingEpochStartBlock(); uint256 endBlock = IStakingAuRa(stakingContract).stakingEpochEndBlock(); uint256 currentRound = currentCollectRound(); if (_getCurrentBlockNumber() > startBlock + collectRoundLength * 3) { // Check whether each validator didn't reveal their number // during the current collection round validators = validatorSetContract.getValidators(); for (i = 0; i < validators.length; i++) { validator = validators[i]; if (!sentReveal(currentRound, validator)) { uint256 poolId = validatorSetContract.idByMiningAddress(validator); _revealSkips[stakingEpoch][poolId]++; } } } // If this is the last collection round in the current staking epoch // and punishing for unreveal is enabled. if ( punishForUnreveal && (_getCurrentBlockNumber() == endBlock || _getCurrentBlockNumber() + collectRoundLength > endBlock) ) { uint256 maxRevealSkipsAllowed = IStakingAuRa(stakingContract).stakeWithdrawDisallowPeriod() / collectRoundLength; if (maxRevealSkipsAllowed > 1) { maxRevealSkipsAllowed -= 2; } else if (maxRevealSkipsAllowed > 0) { maxRevealSkipsAllowed--; } // Check each validator to see if they didn't reveal // their number during the last full `reveals phase` // or if they missed the required number of reveals per staking epoch. validators = validatorSetContract.getValidators(); address[] memory maliciousValidators = new address[](validators.length); uint256 maliciousValidatorsLength = 0; for (i = 0; i < validators.length; i++) { validator = validators[i]; if ( !sentReveal(currentRound, validator) || revealSkips(stakingEpoch, validator) > maxRevealSkipsAllowed ) { // Mark the validator as malicious maliciousValidators[maliciousValidatorsLength++] = validator; } } if (maliciousValidatorsLength > 0) { address[] memory miningAddresses = new address[](maliciousValidatorsLength); for (i = 0; i < maliciousValidatorsLength; i++) { miningAddresses[i] = maliciousValidators[i]; } validatorSetContract.removeMaliciousValidators(miningAddresses); } } // Clear unnecessary info about previous collection round. _clearOldCiphers(currentRound); } // =============================================== Getters ======================================================== /// @dev Returns the length of the commits/reveals phase which is always half of the collection round length. function commitPhaseLength() public view returns(uint256) { return collectRoundLength / 2; } /// @dev Returns the serial number of the current collection round. function currentCollectRound() public view returns(uint256) { return (_getCurrentBlockNumber() - 1) / collectRoundLength; } /// @dev Returns the number of the first block of the current collection round. function currentCollectRoundStartBlock() public view returns(uint256) { return currentCollectRound() * collectRoundLength + 1; } /// @dev Returns the cipher of the validator's number for the specified collection round and the specified validator /// stored by the validator through the `commitHash` function. /// For the past collection rounds the cipher is empty as it's erased by the internal `_clearOldCiphers` function. /// @param _collectRound The serial number of the collection round for which the cipher should be retrieved. /// @param _miningAddress The mining address of validator. function getCipher(uint256 _collectRound, address _miningAddress) public view returns(bytes memory) { uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress); return _ciphers[_collectRound][poolId]; } /// @dev Returns the Keccak-256 hash of the validator's number for the specified collection round and the specified /// validator stored by the validator through the `commitHash` function. Note that for the past collection rounds /// it can return empty results because there was a migration from mining addresses to staking addresses. /// @param _collectRound The serial number of the collection round for which the hash should be retrieved. /// @param _miningAddress The mining address of validator. function getCommit(uint256 _collectRound, address _miningAddress) public view returns(bytes32) { uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress); return _commits[_collectRound][poolId]; } /// @dev Returns the Keccak-256 hash and cipher of the validator's number for the specified collection round /// and the specified validator stored by the validator through the `commitHash` function. /// For the past collection rounds the cipher is empty. Note that for the past collection rounds /// it can return empty results because there was a migration from mining addresses to staking addresses. /// @param _collectRound The serial number of the collection round for which hash and cipher should be retrieved. /// @param _miningAddress The mining address of validator. function getCommitAndCipher( uint256 _collectRound, address _miningAddress ) public view returns(bytes32, bytes memory) { uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress); return (_commits[_collectRound][poolId], _ciphers[_collectRound][poolId]); } /// @dev Returns a boolean flag indicating whether the specified validator has committed their number's hash for the /// specified collection round. Note that for the past collection rounds it can return false-negative results /// because there was a migration from mining addresses to staking addresses (on xDai chain). /// Also, it intentionally returns a false-positive result during the commit phase when the specified /// mining address of a validator is about to be changed. This is needed to prevent committing hash/cipher pair /// by Ethereum node to guarantee that a new validator's node (with a new mining address) won't try to wrongly /// decrypt the cipher stored by the previous node (created by the private key of the previous mining address). /// @param _collectRound The serial number of the collection round for which the checkup should be done. /// @param _miningAddress The mining address of the validator. function isCommitted(uint256 _collectRound, address _miningAddress) public view returns(bool) { uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress); if (poolId != 0 && isCommitPhase()) { (uint256 requestPoolId,) = validatorSetContract.miningAddressChangeRequest(); if (poolId == requestPoolId) { return true; } } return _commits[_collectRound][poolId] != bytes32(0); } /// @dev Returns a boolean flag indicating whether the current phase of the current collection round /// is a `commits phase`. Used by the validator's node to determine if it should commit the hash of /// the number during the current collection round. function isCommitPhase() public view returns(bool) { return ((_getCurrentBlockNumber() - 1) % collectRoundLength) < commitPhaseLength(); } /// @dev Returns a boolean flag indicating if the `initialize` function has been called. function isInitialized() public view returns(bool) { return validatorSetContract != IValidatorSetAuRa(0); } /// @dev Returns a boolean flag indicating whether the current phase of the current collection round /// is a `reveals phase`. Used by the validator's node to determine if it should reveal the number during /// the current collection round. function isRevealPhase() public view returns(bool) { return !isCommitPhase(); } /// @dev Returns a boolean flag of whether the `commitHash` function can be called at the current block /// by the specified validator. Used by the `commitHash` function and the `TxPermission` contract. /// @param _miningAddress The mining address of the validator which tries to call the `commitHash` function. /// @param _numberHash The Keccak-256 hash of validator's number passed to the `commitHash` function. function commitHashCallable(address _miningAddress, bytes32 _numberHash) public view returns(bool) { if (!isCommitPhase()) return false; // must only be called in `commits phase` if (_numberHash == bytes32(0)) return false; if (!validatorSetContract.isValidator(_miningAddress)) return false; if (isCommitted(currentCollectRound(), _miningAddress)) return false; // cannot commit more than once return true; } /// @dev Returns the number of the first block of the next (future) collection round. function nextCollectRoundStartBlock() public view returns(uint256) { uint256 currentBlock = _getCurrentBlockNumber(); uint256 remainingBlocksToNextRound = collectRoundLength - (currentBlock - 1) % collectRoundLength; return currentBlock + remainingBlocksToNextRound; } /// @dev Returns the number of the first block of the next (future) commit phase. function nextCommitPhaseStartBlock() public view returns(uint256) { return nextCollectRoundStartBlock(); } /// @dev Returns the number of the first block of the next (future) reveal phase. function nextRevealPhaseStartBlock() public view returns(uint256) { if (isCommitPhase()) { return currentCollectRoundStartBlock() + commitPhaseLength(); } else { return nextCollectRoundStartBlock() + commitPhaseLength(); } } /// @dev Returns a boolean flag of whether the `revealNumber` function can be called at the current block /// by the specified validator. Used by the `revealNumber` function and the `TxPermission` contract. /// @param _miningAddress The mining address of validator which tries to call the `revealNumber` function. /// @param _number The validator's number passed to the `revealNumber` function. function revealNumberCallable(address _miningAddress, uint256 _number) public view returns(bool) { return _revealNumberCallable(_miningAddress, _number); } /// @dev The same as the `revealNumberCallable` getter (see its description). /// The `revealSecretCallable` was renamed to `revealNumberCallable`, so this function /// is left for backward compatibility with the previous client /// implementation and should be deleted in the future. /// @param _miningAddress The mining address of validator which tries to call the `revealSecret` function. /// @param _number The validator's number passed to the `revealSecret` function. function revealSecretCallable(address _miningAddress, uint256 _number) public view returns(bool) { return _revealNumberCallable(_miningAddress, _number); } /// @dev Returns the number of reveal skips made by the specified validator during the specified staking epoch. /// @param _stakingEpoch The number of staking epoch. /// @param _miningAddress The mining address of the validator. function revealSkips(uint256 _stakingEpoch, address _miningAddress) public view returns(uint256) { uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress); return _revealSkips[_stakingEpoch][poolId]; } /// @dev Returns a boolean flag indicating whether the specified validator has revealed their number for the /// specified collection round. Note that for the past collection rounds it can return false-negative results /// because there was a migration from mining addresses to staking addresses. /// @param _collectRound The serial number of the collection round for which the checkup should be done. /// @param _miningAddress The mining address of the validator. function sentReveal(uint256 _collectRound, address _miningAddress) public view returns(bool) { uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress); return _sentReveal[_collectRound][poolId]; } // ============================================== Internal ======================================================== /// @dev Removes the ciphers of all committed validators for the collection round /// preceding to the specified collection round. /// @param _collectRound The serial number of the collection round. function _clearOldCiphers(uint256 _collectRound) internal { if (_collectRound == 0) { return; } uint256 collectRound = _collectRound - 1; uint256[] storage poolIds = _committedValidators[collectRound]; uint256 poolIdsLength = poolIds.length; for (uint256 i = 0; i < poolIdsLength; i++) { delete _ciphers[collectRound][poolIds[i]]; } poolIds.length = 0; } /// @dev Used by the `revealNumber` function. /// @param _number The validator's number. function _revealNumber(uint256 _number) internal { address miningAddress = msg.sender; require(revealNumberCallable(miningAddress, _number)); require(_getCoinbase() == miningAddress); // make sure validator node is live uint256 poolId = validatorSetContract.idByMiningAddress(miningAddress); currentSeed = currentSeed ^ _number; _sentReveal[currentCollectRound()][poolId] = true; } /// @dev Returns the current `coinbase` address. Needed mostly for unit tests. function _getCoinbase() internal view returns(address) { return block.coinbase; } /// @dev Returns the current block number. Needed mostly for unit tests. function _getCurrentBlockNumber() internal view returns(uint256) { return block.number; } /// @dev Used by the `revealNumberCallable` public getter. /// @param _miningAddress The mining address of validator which tries to call the `revealNumber` function. /// @param _number The validator's number passed to the `revealNumber` function. function _revealNumberCallable(address _miningAddress, uint256 _number) internal view returns(bool) { if (!isRevealPhase()) return false; // must only be called in `reveals phase` bytes32 numberHash = keccak256(abi.encodePacked(_number)); if (numberHash == bytes32(0)) return false; if (!validatorSetContract.isValidator(_miningAddress)) return false; uint256 collectRound = currentCollectRound(); if (sentReveal(collectRound, _miningAddress)) { return false; // cannot reveal more than once during the same collectRound } if (numberHash != getCommit(collectRound, _miningAddress)) { return false; // the hash must be commited } return true; } }
Returns a boolean flag of whether the `revealNumber` function can be called at the current block by the specified validator. Used by the `revealNumber` function and the `TxPermission` contract. _miningAddress The mining address of validator which tries to call the `revealNumber` function. _number The validator's number passed to the `revealNumber` function.
function revealNumberCallable(address _miningAddress, uint256 _number) public view returns(bool) { return _revealNumberCallable(_miningAddress, _number); }
5,364,747
contract ShinySquirrels { // all the things uint private minDeposit = 10 finney; uint private maxDeposit = 5 ether; uint private baseFee = 5; uint private baseMultiplier = 100; uint private maxMultiplier = 160; uint private currentPosition = 0; uint private balance = 0; uint private feeBalance = 0; uint private totalDeposits = 0; uint private totalPaid = 0; uint private totalSquirrels = 0; uint private totalShinyThings = 0; uint private totalSprockets = 0; uint private totalStars = 0; uint private totalHearts = 0; uint private totalSkips = 0; address private owner = msg.sender; struct PlayerEntry { address addr; uint deposit; uint paid; uint multiplier; uint fee; uint skip; uint squirrels; uint shinyThings; uint sprockets; uint stars; uint hearts; } struct PlayerStat { address addr; uint entries; uint deposits; uint paid; uint skips; uint squirrels; uint shinyThings; uint sprockets; uint stars; uint hearts; } // player entries in the order received PlayerEntry[] private players; // The Line of players, keeping track as new players cut in... uint[] theLine; // individual player totals mapping(address => PlayerStat) private playerStats; // Shiny new contract, no copy & paste here! function ShinySquirrels() { owner = msg.sender; } function totals() constant returns(uint playerCount, uint currentPlaceInLine, uint playersWaiting, uint totalDepositsInFinneys, uint totalPaidOutInFinneys, uint squirrelFriends, uint shinyThingsFound, uint sprocketsCollected, uint starsWon, uint heartsEarned, uint balanceInFinneys, uint feeBalanceInFinneys) { playerCount = players.length; currentPlaceInLine = currentPosition; playersWaiting = waitingForPayout(); totalDepositsInFinneys = totalDeposits / 1 finney; totalPaidOutInFinneys = totalPaid / 1 finney; squirrelFriends = totalSquirrels; shinyThingsFound = totalShinyThings; sprocketsCollected = totalSprockets; starsWon = totalStars; heartsEarned = totalHearts; balanceInFinneys = balance / 1 finney; feeBalanceInFinneys = feeBalance / 1 finney; } function settings() constant returns(uint minimumDepositInFinneys, uint maximumDepositInFinneys) { minimumDepositInFinneys = minDeposit / 1 finney; maximumDepositInFinneys = maxDeposit / 1 finney; } function playerByAddress(address addr) constant returns(uint entries, uint depositedInFinney, uint paidOutInFinney, uint skippedAhead, uint squirrels, uint shinyThings, uint sprockets, uint stars, uint hearts) { entries = playerStats[addr].entries; depositedInFinney = playerStats[addr].deposits / 1 finney; paidOutInFinney = playerStats[addr].paid / 1 finney; skippedAhead = playerStats[addr].skips; squirrels = playerStats[addr].squirrels; shinyThings = playerStats[addr].shinyThings; sprockets = playerStats[addr].sprockets; stars = playerStats[addr].stars; hearts = playerStats[addr].hearts; } // current number of players still waiting for their payout function waitingForPayout() constant private returns(uint waiting) { waiting = players.length - currentPosition; } // the total payout this entry in line will receive function entryPayout(uint index) constant private returns(uint payout) { payout = players[theLine[index]].deposit * players[theLine[index]].multiplier / 100; } // the payout amount still due to this entry in line function entryPayoutDue(uint index) constant private returns(uint payoutDue) { // subtract the amount they've been paid from the total they are to receive payoutDue = entryPayout(index) - players[theLine[index]].paid; } // public interface to the line of players function lineOfPlayers(uint index) constant returns (address addr, uint orderJoined, uint depositInFinney, uint payoutInFinney, uint multiplierPercent, uint paid, uint skippedAhead, uint squirrels, uint shinyThings, uint sprockets, uint stars, uint hearts) { PlayerEntry player = players[theLine[index]]; addr = player.addr; orderJoined = theLine[index]; depositInFinney = player.deposit / 1 finney; payoutInFinney = depositInFinney * player.multiplier / 100; multiplierPercent = player.multiplier; paid = player.paid / 1 finney; skippedAhead = player.skip; squirrels = player.squirrels; shinyThings = player.shinyThings; sprockets = player.sprockets; stars = player.stars; hearts = player.hearts; } function () { play(); } function play() { uint deposit = msg.value; // in wei // validate deposit is in range if(deposit < minDeposit || deposit > maxDeposit) { msg.sender.send(deposit); return; } uint multiplier = baseMultiplier; // percent uint fee = baseFee; // percent uint skip = 0; uint squirrels = 0; uint shinyThings = 0; uint sprockets = 0; uint stars = 0; uint hearts = 0; if(players.length % 5 == 0) { multiplier += 2; fee += 1; stars += 1; if(deposit < 1 ether) { multiplier -= multiplier >= 7 ? 7 : multiplier; fee -= fee >= 1 ? 1 : 0; shinyThings += 1; } if(deposit >= 1 && waitingForPayout() >= 10) { // at least 10 players waiting skip += 4; fee += 3; } if(deposit >= 2 ether && deposit <= 3 ether) { multiplier += 3; fee += 2; hearts += 1; } if(deposit >= 3 ether) { stars += 1; } } else if (players.length % 5 == 1) { multiplier += 4; fee += 2; squirrels += 1; if(deposit < 1 ether) { multiplier += 6; fee += 3; squirrels += 1; } if(deposit >= 2 ether) { if(waitingForPayout() >= 20) { // at least 20 players waiting skip += waitingForPayout() / 2; // skip half of them fee += 2; shinyThings += 1; } multiplier += 4; fee += 4; hearts += 1; } if(deposit >= 4 ether) { multiplier += 1; fee -= fee >= 1 ? 1 : 0; skip += 1; hearts += 1; stars += 1; } } else if (players.length % 5 == 2) { multiplier += 7; fee += 6; sprockets += 1; if(waitingForPayout() >= 10) { // at least 10 players waiting multiplier -= multiplier >= 8 ? 8 : multiplier; fee -= fee >= 1 ? 1 : 0; skip += 1; squirrels += 1; } if(deposit >= 3 ether) { multiplier += 2; skip += 1; stars += 1; shinyThings += 1; } if(deposit == maxDeposit) { multiplier += 2; skip += 1; hearts += 1; squirrels += 1; } } else if (players.length % 5 == 3) { multiplier -= multiplier >= 5 ? 5 : multiplier; // on noes! fee += 0; skip += 3; // oh yay! shinyThings += 1; if(deposit < 1 ether) { multiplier -= multiplier >= 5 ? 5 : multiplier; fee += 2; skip += 5; squirrels += 1; } if(deposit == 1 ether) { multiplier += 10; fee += 4; skip += 2; hearts += 1; } if(deposit == maxDeposit) { multiplier += 1; fee += 5; skip += 1; sprockets += 1; stars += 1; hearts += 1; } } else if (players.length % 5 == 4) { multiplier += 2; fee -= fee >= 1 ? 1 : fee; squirrels += 1; if(deposit < 1 ether) { multiplier += 3; fee += 2; skip += 3; } if(deposit >= 2 ether) { multiplier += 2; fee += 2; skip += 1; stars += 1; } if(deposit == maxDeposit/2) { multiplier += 2; fee += 5; skip += 3; shinyThings += 1; sprockets += 1; } if(deposit >= 3 ether) { multiplier += 1; fee += 1; skip += 1; sprockets += 1; hearts += 1; } } // track the accumulated bonus goodies! playerStats[msg.sender].hearts += hearts; playerStats[msg.sender].stars += stars; playerStats[msg.sender].squirrels += squirrels; playerStats[msg.sender].shinyThings += shinyThings; playerStats[msg.sender].sprockets += sprockets; // track cummulative awarded goodies totalHearts += hearts; totalStars += stars; totalSquirrels += squirrels; totalShinyThings += shinyThings; totalSprockets += sprockets; // got squirrels? skip in front of that many players! skip += playerStats[msg.sender].squirrels; // one squirrel ran away! playerStats[msg.sender].squirrels -= playerStats[msg.sender].squirrels >= 1 ? 1 : 0; // got stars? 2% multiplier bonus for every star! multiplier += playerStats[msg.sender].stars * 2; // got hearts? -2% fee for every heart! fee -= playerStats[msg.sender].hearts; // got sprockets? 1% multiplier bonus and -1% fee for every sprocket! multiplier += playerStats[msg.sender].sprockets; fee -= fee > playerStats[msg.sender].sprockets ? playerStats[msg.sender].sprockets : fee; // got shiny things? skip 1 more player and -1% fee! if(playerStats[msg.sender].shinyThings >= 1) { skip += 1; fee -= fee >= 1 ? 1 : 0; } // got a heart, star, squirrel, shiny thin, and sprocket?!? 50% bonus multiplier!!! if(playerStats[msg.sender].hearts >= 1 && playerStats[msg.sender].stars >= 1 && playerStats[msg.sender].squirrels >= 1 && playerStats[msg.sender].shinyThings >= 1 && playerStats[msg.sender].sprockets >= 1) { multiplier += 30; } // got a heart and a star? trade them for +20% multiplier!!! if(playerStats[msg.sender].hearts >= 1 && playerStats[msg.sender].stars >= 1) { multiplier += 15; playerStats[msg.sender].hearts -= 1; playerStats[msg.sender].stars -= 1; } // got a sprocket and a shiny thing? trade them for 5 squirrels! if(playerStats[msg.sender].sprockets >= 1 && playerStats[msg.sender].shinyThings >= 1) { playerStats[msg.sender].squirrels += 5; playerStats[msg.sender].sprockets -= 1; playerStats[msg.sender].shinyThings -= 1; } // stay within profitable and safe limits if(multiplier > maxMultiplier) { multiplier == maxMultiplier; } // keep power players in check so regular players can still win some too if(waitingForPayout() > 15 && skip > waitingForPayout()/2) { // limit skip to half of waiting players skip = waitingForPayout() / 2; } // ledgers within ledgers feeBalance += deposit * fee / 100; balance += deposit - deposit * fee / 100; totalDeposits += deposit; // prepare players array for a new entry uint playerIndex = players.length; players.length += 1; // make room in The Line for one more uint lineIndex = theLine.length; theLine.length += 1; // skip ahead if you should be so lucky! (skip, lineIndex) = skipInLine(skip, lineIndex); // record the players entry players[playerIndex].addr = msg.sender; players[playerIndex].deposit = deposit; players[playerIndex].multiplier = multiplier; players[playerIndex].fee = fee; players[playerIndex].squirrels = squirrels; players[playerIndex].shinyThings = shinyThings; players[playerIndex].sprockets = sprockets; players[playerIndex].stars = stars; players[playerIndex].hearts = hearts; players[playerIndex].skip = skip; // add the player to The Line at whatever position they snuck in at theLine[lineIndex] = playerIndex; // track players cumulative stats playerStats[msg.sender].entries += 1; playerStats[msg.sender].deposits += deposit; playerStats[msg.sender].skips += skip; // track total game skips totalSkips += skip; // issue payouts while the balance allows // rolling payouts occur as long as the balance is above zero uint nextPayout = entryPayoutDue(currentPosition); uint payout; while(balance > 0) { if(nextPayout <= balance) { // the balance is great enough to pay the entire next balance due // pay the balance due payout = nextPayout; } else { // the balance is above zero, but less than the next balance due // send them everything available payout = balance; } // issue the payment players[theLine[currentPosition]].addr.send(payout); // mark the amount paid players[theLine[currentPosition]].paid += payout; // keep a global tally playerStats[players[theLine[currentPosition]].addr].paid += payout; balance -= payout; totalPaid += payout; // move to the next position in line if the last entry got paid out completely if(balance > 0) { currentPosition++; nextPayout = entryPayoutDue(currentPosition); } } } // jump in line, moving entries back towards the end one at a time // presumes the line length has already been increased to accomodate the newcomer // return the the number of positions skipped and the index of the vacant position in line function skipInLine(uint skip, uint currentLineIndex) private returns (uint skipped, uint newLineIndex) { // check for at least 1 player in line plus this new entry if(skip > 0 && waitingForPayout() > 2) { // -2 because we don't want to count the new empty slot at the end of the list if(skip > waitingForPayout()-2) { skip = waitingForPayout()-2; } // move entries forward one by one uint i = 0; while(i < skip) { theLine[currentLineIndex-i] = theLine[currentLineIndex-1-i]; i++; } // don't leave a duplicate copy of the last entry processed delete(theLine[currentLineIndex-i]); // the newly vacant position is i slots from the end newLineIndex = currentLineIndex-i; } else { // no change newLineIndex = currentLineIndex; skip = 0; } skipped = skip; } function DynamicPyramid() { // Rubixi god-code, j/k :-P playerStats[msg.sender].squirrels = 0; playerStats[msg.sender].shinyThings = 0; playerStats[msg.sender].sprockets = 0; playerStats[msg.sender].stars = 0; playerStats[msg.sender].hearts = 0; } function collectFees() { if(msg.sender != owner) { throw; } // game balance will always be zero due to automatic rolling payouts if(address(this).balance > balance + feeBalance) { // collect any funds outside of the game balance feeBalance = address(this).balance - balance; } owner.send(feeBalance); feeBalance = 0; } function updateSettings(uint newMultiplier, uint newMaxMultiplier, uint newFee, uint newMinDeposit, uint newMaxDeposit, bool collect) { // adjust the base settings within a small and limited range as the game matures and ether prices change if(msg.sender != owner) throw; if(newMultiplier < 80 || newMultiplier > 120) throw; if(maxMultiplier < 125 || maxMultiplier > 200) throw; if(newFee < 0 || newFee > 15) throw; if(minDeposit < 1 finney || minDeposit > 1 ether) throw; if(maxDeposit < 1 finney || maxDeposit > 25 ether) throw; if(collect) collectFees(); baseMultiplier = newMultiplier; maxMultiplier = newMaxMultiplier; baseFee = newFee; minDeposit = newMinDeposit; maxDeposit = newMaxDeposit; } }
current number of players still waiting for their payout
function waitingForPayout() constant private returns(uint waiting) { waiting = players.length - currentPosition; }
12,966,798
./partial_match/80001/0xD37583FC57dA40A5fA8d33Ce9ab13C430E39DBBA/sources/ERC721CollectionV2.sol
Returns a rarity's maximum supply will revert if the rarity is out of the RARITY enum bounds return Max supply of the rarity given/
function getRarityValue(RARITY _rarity) public pure returns (uint256) { if (_rarity == RARITY.common) { return 100000; return 10000; return 5000; return 1000; return 100; return 10; return 1; } revert("#BCV2#getRarityValue: INVALID_RARITY"); }
8,819,541
./partial_match/288/0x00Be23692bF0114eEec56AbF1161ec46889a894c/sources/contracts/Ola/Peripheral/Liquidator/LiquidatorBase.sol
TODO : Using 'cToken.borrowBalanceCurrent' will retrieve the 'borrowBalanceStored' after accruing interest amountOut desired from swap Removing a bit of dust to avoid rounding errors repayAmount = maxClose - 1e1;
function getSafeRepayAmount(address cTokenBorrow, address cTokenCollateral, address borrower, uint repayAmount) internal returns (uint) { require(CTokenInterfaceForLiquidator(cTokenBorrow).accrueInterest() == 0, "borrow accrue"); if (cTokenBorrow != cTokenCollateral) { require(CTokenInterfaceForLiquidator(cTokenCollateral).accrueInterest() == 0, "collateral accrue"); } uint totalBorrow = CTokenInterfaceForLiquidator(cTokenBorrow).borrowBalanceStored(borrower); if (repayAmount == 0) { repayAmount = maxClose; require(repayAmount <= maxClose, "repayAmount too big"); } return repayAmount; }
16,907,058
pragma solidity ^0.4.16; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract EBanker is owned { // Public variables of the token string public name = "EBanker"; string public symbol = "EBC"; uint8 public decimals = 18; uint256 public totalSupply = 0; uint256 public sellPrice = 1065; uint256 public buyPrice = 1065; bool public released = false; /// contract that is allowed to create new tokens and allows unlift the transfer limits on this token address public crowdsaleAgent; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function EBanker() public { } modifier canTransfer() { require(released); _; } modifier onlyCrowdsaleAgent() { require(msg.sender == crowdsaleAgent); _; } function releaseTokenTransfer() public onlyCrowdsaleAgent { released = true; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) canTransfer internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Check if sender is frozen require(!frozenAccount[_from]); // Check if recipient is frozen require(!frozenAccount[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyCrowdsaleAgent public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) canTransfer public { require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It&#39;s important to do this last to avoid recursion attacks } /// @dev Set the contract that can call release and make the token transferable. /// @param _crowdsaleAgent crowdsale contract address function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner public { crowdsaleAgent = _crowdsaleAgent; } } contract Killable is owned { function kill() onlyOwner { selfdestruct(owner); } } contract EBankerICO is owned, Killable { /// The token we are selling EBanker public token; /// Current State Name string public state = "Pre ICO"; /// the UNIX timestamp start date of the crowdsale uint public startsAt = 1521748800; /// the UNIX timestamp end date of the crowdsale uint public endsAt = 1522612800; /// the price of token uint256 public TokenPerETH = 1065; /// per user limit of buying tokens. uint256 public LimitPerUserEBC = 100000 * 10 ** 18; /// Has this crowdsale been finalized bool public finalized = false; /// the number of tokens already sold through this contract uint public tokensSold = 0; /// the number of ETH raised through this contract uint public weiRaised = 0; /// How many distinct addresses have invested uint public investorCount = 0; /// How much ETH each address has invested to this crowdsale mapping (address => uint256) public investedAmountOf; /// How much tokens this crowdsale has credited for each investor address mapping (address => uint256) public tokenAmountOf; /// A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount); /// Crowdsale end time has been changed event EndsAtChanged(uint endsAt); /// Calculated new price event RateChanged(uint oldValue, uint newValue); function EBankerICO(address _token) { token = EBanker(_token); } function investInternal(address receiver) private { require(!finalized); require(startsAt <= now && endsAt > now); require(tokenAmountOf[receiver] + msg.value * TokenPerETH <= LimitPerUserEBC); if(investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor uint tokensAmount = msg.value * TokenPerETH; investedAmountOf[receiver] += msg.value; tokenAmountOf[receiver] += tokensAmount; // Update totals tokensSold += tokensAmount; weiRaised += msg.value; // Tell us invest was success Invested(receiver, msg.value, tokensAmount); token.mintToken(receiver, tokensAmount); } function buy() public payable { investInternal(msg.sender); } function() payable { buy(); } function setEndsAt(uint time) onlyOwner { require(!finalized); endsAt = time; EndsAtChanged(endsAt); } function setRate(uint value) onlyOwner { require(!finalized); require(value > 0); RateChanged(TokenPerETH, value); TokenPerETH = value; } function finalize(address receiver) public onlyOwner { // Finalized Pre ICO crowdsele. finalized = true; // Make tokens Transferable token.releaseTokenTransfer(); // Transfer Fund to owner&#39;s address receiver.transfer(this.balance); } }
This generates a public event on the blockchain that will notify clients / Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
function EBanker() public { }
1,969,899
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; 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); } function fromAddress(address addr) internal pure returns(string memory) { bytes20 addrBytes = bytes20(addr); bytes16 hexAlphabet = "0123456789abcdef"; bytes memory result = new bytes(42); result[0] = '0'; result[1] = 'x'; for (uint i = 0; i < 20; i++) { result[i * 2 + 2] = hexAlphabet[uint8(addrBytes[i] >> 4)]; result[i * 2 + 3] = hexAlphabet[uint8(addrBytes[i] & 0x0f)]; } return string(result); } } /** * @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; } } 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 Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } /* * @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 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; } } /** * @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; } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @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; } /** * @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); } /** * _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); } /** * * @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)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * 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_) public { _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 (uint 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 (uint 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 ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } contract DreamBeats is Ownable, ERC1155, ReentrancyGuard { using SafeMath for uint256; using Strings for string; using Address for address payable; // key: LPID, value: boolean lpDropped | true iff drop is live for token with LPID mapping (uint256 => bool) private _lpDropped; // key: LPID, value: totalSupply of that LP. mapping(uint256 => uint256) public totalSupply; // key: LPID, value: string that is that LPs name. mapping(uint256 => string) public lpName; // key: address, value: isBlacklisted mapping(address => bool) public lpNameBlacklist; // Supply restriction on lp prints, 0 indexed, so 150 per lp uint256 constant public MAX_DREAM_SUPPLY = 149; // bonding curve values uint256 public A = 300; uint256 public B = 8; uint256 public C = 8; uint256 public SIG_DIGITS = 4; // bit things uint256 BITSHIFT_AMOUNT = 8; // baseURI for token metadata url, override ERC1155 string _baseURI = "https://dreambeats.io/metadata/"; // Contract name string public name = "DreamBeats"; // Contract symbol string public symbol = "DB"; // contract state bool isPaused = true; constructor() ERC1155("") {} modifier whenNotPaused() { require(!isPaused, "Contract is paused, we're adjusting something, please try again in a bit!"); _; } modifier whenPaused() { require(isPaused, "Contract is not paused."); _; } /** * MINTING */ /** * @dev function to mint og lp or lp with lpID 'lpID' * * Requirements: * - lpID drop must be live * - total supply of lpID must be less than MAX_DREAM_SUPPLY * - msg.value must be AT LEAST the current print price */ function mint(uint256 lpID) public payable nonReentrant whenNotPaused returns (uint256) { // Confirm drop is live for lpID require(_lpDropped[lpID] == true, "Drop not live"); // verify totalSupply of lp is under MAX_DREAM_SUPPLY require(totalSupply[lpID] < MAX_DREAM_SUPPLY, "Max supply reached"); // Get price to mint current print, verify that the value of tx has enough uint256 newSupply = totalSupply[lpID] + 1; // 0 indexed print prices uint256 printPrice = getPrintPrice(newSupply - 1); require(msg.value >= printPrice, "Insufficient funds"); // Set Supply to newSupply totalSupply[lpID] = newSupply; if (totalSupply[lpID] == 1) { // The case where they are minting the og LP //Mint lpID _mint(msg.sender, lpID, 1, ""); // refund extra eth sent _refundSender(printPrice); return lpID; } // compute tokenID uint256 tokenID = getPrintTokenIdFromLpId(lpID); // Mint token _mint(msg.sender, tokenID, 1, ""); // Refund buyer for any extra eth sent _refundSender(printPrice); return tokenID; } /** * FUNCTIONS FOR ORIGINAL LP OWNERS */ /** * @dev function to name lp with 'lpID' 'lpNameToSet' * * Requirements: * - msg.sender must own the original LP * - lpNameToSet must be under 32 bytes * * Note: string of size 32 bytes not always equivalent to length of 32 */ function nameLp(uint256 lpId, string memory lpNameToSet) public whenNotPaused { require(!lpNameBlacklist[msg.sender], "You are blacklisted from naming."); require(balanceOf(msg.sender, lpId) == 1, "You don't own the og LP!"); require(bytes(lpNameToSet).length <= 32, "Max name size is 32 bytes."); lpName[lpId] = lpNameToSet; } /** * PUBLIC GETTERS */ /** * @dev get price for print 'printNum' * * Note: printNum == totalSupply at time of minting since we're 0 indexed * */ function getPrintPrice(uint256 printNum) public view returns (uint256 price) { uint256 decimals = 10 ** SIG_DIGITS; // A + Bx + Cx^2 price = A.add(B.mul(printNum)).add(C.mul(printNum ** 2)); // convert to wei price = price.mul(1 ether).div(decimals); } /** * @dev get totalSupply of lp with 'lpID' * */ function lpPrintsSupply(uint256 lpID) public view returns (uint256) { return totalSupply[lpID]; } /** * @dev get print tokenID for original lp with id lpID * * Note: overlap possible bc of the small shift we use but we're not going to drop that many. * */ function getPrintTokenIdFromLpId(uint256 lpID) public view returns (uint256) { return (lpID + 1) << BITSHIFT_AMOUNT; } /** * @dev get original lp lpID for print tokenID * * Note: overlap possible bc of the small shift we use but we're not going to drop that many. * */ function getLpIdfromPrintTokenId(uint256 printID) public view returns (uint256) { return (printID >> BITSHIFT_AMOUNT) - 1; } /** * @dev is token with tokenID an original Lp? * * Note: the two ranges can overlap but we're not going to drop that many. * */ function isOriginalLp(uint256 tokenID) public pure returns (bool) { // 256 is 1 << 8, smallest possible id a token can be at until overflow which we will never hit // imagine doing over 256 of these clips we would die return (tokenID < 256); } /** * @dev get URI for token '_id * */ function uri(uint256 _id) external override view returns (string memory) { if (!isOriginalLp(_id)) { require(totalSupply[getLpIdfromPrintTokenId(_id)] > 0, "URI query for nonexistent token"); } else { require(totalSupply[_id] > 0, "URI query for nonexistent token"); } return Strings.strConcat( _baseURI, Strings.uint2str(_id) ); } /** * INTERNAL UTILITY FUNCTIONS */ /** * @dev refund msg.value in excess of 'printPrice' * */ function _refundSender(uint256 printPrice) internal { if (msg.value.sub(printPrice) > 0) { msg.sender.sendValue(msg.value.sub(printPrice)); } } /** * OWNER UTILITY FUNCTIONS */ /** * @dev adjust bonding curve, set new A, B, C, and SIG_DIGITS * */ function adjustBondingCurve(uint256 a, uint256 b, uint256 c, uint256 sigdigits) external onlyOwner whenPaused { (A, B, C, SIG_DIGITS) = (a, b, c, sigdigits); } /** * @dev set _baseURI to newBaseURI * */ function updateBaseURI(string memory newBaseURI) external onlyOwner whenPaused { _baseURI = newBaseURI; } /** * @dev drop lp with lpIDs in lplist * * require: none of the lpIDs can already have been dropped * */ function dropLP(uint[] memory lpList) external onlyOwner whenPaused { for (uint i=0; i<lpList.length; i++) { require(!_lpDropped[lpList[i]], "Drop is already live."); _lpDropped[lpList[i]] = true; } } /** * @dev drop lp with lpIDs in lplist and mint the original LP * * require: none of the lpIDs can already have been dropped * */ function dropLPAndMint(uint[] memory lpList) external onlyOwner whenPaused { for (uint i=0; i<lpList.length; i++) { require(!_lpDropped[lpList[i]], "Drop is already live."); _lpDropped[lpList[i]] = true; // set totalSupply to 1 totalSupply[lpList[i]] = 1; //Mint lpID _mint(msg.sender, lpList[i], 1, ""); } } /** * @dev set BITSHIFT_AMOUNT to b * */ function setBitShift(uint256 b) external onlyOwner whenPaused { BITSHIFT_AMOUNT = b; } /** * @dev withdraw all funds * */ function withdraw() external onlyOwner nonReentrant { msg.sender.sendValue(address(this).balance); } /** * @dev set isPaused to pause * * note: pausing is required before making any changes to the contract including drops * */ function setPause(bool pause) external onlyOwner { isPaused = pause; } /** * @dev set name of lpID back to default and blacklist address _addressToBlacklist that named it from renaming. * * note: we hope we never have to use this. * */ function resetNameAndBlackList(uint256 lpID, address _addressToBlacklist) external onlyOwner whenPaused { lpName[lpID] = ""; lpNameBlacklist[_addressToBlacklist] = true; } /** * @dev remove address _addressToRemove from blacklist * * */ function removeAddressFromBlacklist(address _addressToRemove) external onlyOwner whenPaused { lpNameBlacklist[_addressToRemove] = false; } }
function to name lp with 'lpID' 'lpNameToSet' Requirements: - msg.sender must own the original LP - lpNameToSet must be under 32 bytes Note: string of size 32 bytes not always equivalent to length of 32/
function nameLp(uint256 lpId, string memory lpNameToSet) public whenNotPaused { require(!lpNameBlacklist[msg.sender], "You are blacklisted from naming."); require(balanceOf(msg.sender, lpId) == 1, "You don't own the og LP!"); require(bytes(lpNameToSet).length <= 32, "Max name size is 32 bytes."); lpName[lpId] = lpNameToSet; }
615,894
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; import "../proto/NftTransfer.sol"; import "../proto/Ack.sol"; import "../core/02-client/ClientManager.sol"; import "../libraries/04-packet/Packet.sol"; import "../libraries/30-nft-transfer/NftTransfer.sol"; import "../libraries/utils/Bytes.sol"; import "../libraries/utils/Strings.sol"; import "../interfaces/IPacket.sol"; import "../interfaces/ITransfer.sol"; import "../interfaces/IERC1155Bank.sol"; import "../interfaces/IAccessManager.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; contract MockTransferUpgrade is Initializable, ITransfer, OwnableUpgradeable { using Strings for *; using Bytes for *; string private constant PORT = "NFT"; string private constant PREFIX = "nft"; IPacket public packet; IClientManager public clientManager; mapping(uint256 => TransferDataTypes.OriginNFT) public traces; uint256 public version; /** * @notice Event triggered when the nft mint * @param srcTokenId the token id of the nft transferred in the cross-chain * @param tokenId newly generated token id * @param uri uri of nft */ event Mint(string srcTokenId, uint256 tokenId, string uri); /** * @notice Event triggered when the nft burn * @param srcTokenId the token id of the nft transferred in the cross-chain * @param tokenId newly generated token id * @param uri uri of nft */ event Burn(string srcTokenId, uint256 tokenId, string uri); // check if caller is clientManager modifier onlyPacket() { require(msg.sender == address(packet), "caller not packet contract"); _; } function setVersion(uint256 _version) public { version = _version; } function initialize( address packetContract, address clientMgrContract ) public initializer { packet = IPacket(packetContract); clientManager = IClientManager(clientMgrContract); } /** * @notice this function is to send nft and construct data packet * @param transferData Send the data needed by nft */ function sendTransfer(TransferDataTypes.TransferData calldata transferData) external override { string memory sourceChain = clientManager.getChainName(); require( !sourceChain.equals(transferData.destChain), "sourceChain can't equal to destChain" ); bool awayFromOrigin = isAwayFromOrigin( transferData.class, transferData.destChain ); NftTransfer.Data memory packetData; if (awayFromOrigin) { // not support } else { // nft is be closed to origin // burn nft require( _burn( transferData.destContract.parseAddr(), msg.sender, transferData.tokenId, uint256(1) ), "burn nft failed" ); //delete the binding relationship between origin hft and mint's nft in erc1155 // and return the origin nft TransferDataTypes.OriginNFT memory nft = unbind( transferData.tokenId ); packetData = NftTransfer.Data({ class: nft.class, id: nft.id, uri: nft.uri, sender: Bytes.addressToString(msg.sender), receiver: transferData.receiver, awayFromOrigin: awayFromOrigin, destContract: transferData.destContract }); emit Burn(nft.id, transferData.tokenId, nft.uri); } // send packet PacketTypes.Packet memory crossPacket = PacketTypes.Packet({ sequence: packet.getNextSequenceSend( sourceChain, transferData.destChain ), port: PORT, sourceChain: sourceChain, destChain: transferData.destChain, relayChain: transferData.relayChain, data: NftTransfer.encode(packetData) }); packet.sendPacket(crossPacket); } /** * @notice this function is to receive packet * @param pac Data package containing nft data onlyAuthorizee(ON_RECVPACKET_ROLE, address(packet)) */ function onRecvPacket(PacketTypes.Packet calldata pac) external override returns (bytes memory) { bind(uint256(1), "nft/irishub/dog", "taidy", "www.test.com"); return bytes("hello"); } /** * @notice This method is start ack method * @param pac Packets transmitted * @param acknowledgement ack */ function onAcknowledgementPacket( PacketTypes.Packet calldata pac, bytes calldata acknowledgement ) external override onlyPacket { if (!_isSuccessAcknowledgement(acknowledgement)) { _refundTokens(NftTransfer.decode(pac.data)); } } /// private functions /// /** * @notice this function is to destroys `amount` tokens of token type `id` from `account` * @param account address of the account to assign the token to * @param id token id * @param amount amount of tokens to create */ function _burn( address destContract, address account, uint256 id, uint256 amount ) private returns (bool) { try IERC1155Bank(destContract).burn(account, id, amount) { return true; } catch (bytes memory) { return false; } } /** * @notice this function is to create `amount` tokens of token type `id`, and assigns them to `account`. * @param account address of the account to assign the token to * @param id token id * @param amount amount of tokens to create * @param data metadata of the nft */ function _mint( address destContract, address account, uint256 id, uint256 amount, bytes memory data ) private returns (bool) { try IERC1155Bank(destContract).mint(account, id, amount, data) { return true; } catch (bytes memory) { return false; } } /** * @notice this function is to create ack * @param success success or not */ function _newAcknowledgement(bool success, string memory errMsg) private pure returns (bytes memory) { Acknowledgement.Data memory ack; if (success) { ack.result = hex"01"; } else { ack.error = errMsg; } return Acknowledgement.encode(ack); } /** * @notice this function is return a successful ack * @param acknowledgement ack */ function _isSuccessAcknowledgement(bytes memory acknowledgement) private pure returns (bool) { Acknowledgement.Data memory ack = Acknowledgement.decode( acknowledgement ); return Bytes.equals(ack.result, hex"01"); } /** * @notice this function is refund nft * @param data Data in the transmitted packet */ function _refundTokens(NftTransfer.Data memory data) private { uint256 tokenId = genTokenId(data.class, data.id); _mint( data.destContract.parseAddr(), data.sender.parseAddr(), tokenId, uint256(1), bytes(data.uri) ); } /** * @notice determineAwayFromOrigin determine whether nft is sent from the source chain or sent back to the source chain from other chains * example : * -- not has prefix * 1. A -> B class:class | sourceChain:A | destChain:B |awayFromOrigin = true * -- has prefix * 1. B -> C class:nft/A/B/class | sourceChain:B | destChain:C |awayFromOrigin = true A!=destChain * 2. C -> B class:nft/A/B/C/class | sourceChain:C | destChain:B |awayFromOrigin = false B=destChain * 3. B -> A class:nft/A/B/class | sourceChain:B | destChain:A |awayFromOrigin = false A=destChain * @param class nft category * @param destChain destination chain */ function isAwayFromOrigin(string memory class, string memory destChain) private pure returns (bool) { if (!Strings.startsWith(class.toSlice(), PREFIX.toSlice())) { return true; } Strings.slice memory delimSlice = "/".toSlice(); Strings.slice memory classSlice = class.toSlice(); string memory target; for (uint256 i = 0; i < 3; i++) { target = classSlice.rsplit(delimSlice).toString(); } return !Strings.equals(target, destChain); } /** * @notice calculate the hash of scNft and id, take the high 128 bits, and concatenate them into new 32-byte data * example : tokenId := high128(hash(nft/wenchang/nftclass)) + high128(hash(id)) * @param newClassStr the class name of the newly generated nft,ex. nft/{originChain}/{....}/nftClass * @param originNftId nft id from the original chain */ function genTokenId(string memory newClassStr, string memory originNftId) private pure returns (uint256) { // calculate sha256 bytes memory tokenId = Bytes.concat( Bytes.cutBytes32(sha256(bytes(newClassStr))), Bytes.cutBytes32(sha256(bytes(originNftId))) ); return Bytes.bytes32ToUint(tokenId.toBytes32()); } /** * @notice establish a binding relationship between origin nft and mint's nft in erc1155 * @param tokenId token Id * @param nftClass class of origin NFT * @param id id of origin NFT * @param _uri uri of origin NFT */ function bind( uint256 tokenId, string memory nftClass, string memory id, string memory _uri ) private { traces[tokenId] = TransferDataTypes.OriginNFT(nftClass, id, _uri); } /** * @notice Delete the binding relationship between origin hft and mint's nft in erc1155 * @param tokenId token Id */ function unbind(uint256 tokenId) private returns (TransferDataTypes.OriginNFT memory nft) { nft = traces[tokenId]; delete traces[tokenId]; } function getBinding(uint256 tokenId) external view returns (TransferDataTypes.OriginNFT memory) { return traces[tokenId]; } }
this function is return a successful ack acknowledgement ack/
function _isSuccessAcknowledgement(bytes memory acknowledgement) private pure returns (bool) { Acknowledgement.Data memory ack = Acknowledgement.decode( acknowledgement ); return Bytes.equals(ack.result, hex"01"); }
2,513,323
./full_match/137/0x3f9c1729E0D478b37Bf377e2ada1de09fB8e3E2E/sources/AggregationExecutor.sol
given some amount of an asset and pool 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, "DMMLibrary: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "DMMLibrary: INSUFFICIENT_LIQUIDITY"); amountB = amountA.mul(reserveB) / reserveA; }
3,758,757
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ 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; } } interface IStrategy { function rewards() external view returns (address); function gauge() external view returns (address); function underlying() external view returns (address); function timelock() external view returns (address); function deposit() external; function withdraw(uint256) external; function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function harvest() external; function salvage(address) external; function setTimelock(address _timelock) external; function setGovernance(address _governance) external; function setTreasury(address _treasury) external; } interface ITimelock { function MINIMUM_DELAY() external view returns (uint); function MAXIMUM_DELAY() external view returns (uint); function delay() external view returns (uint); } /** * @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; } } /* * @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 IERC20Lib { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies 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" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Lib is Context, IERC20Lib { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @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 SafeERC20Lib { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20Lib token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20Lib 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( IERC20Lib 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( IERC20Lib 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( IERC20Lib 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(IERC20Lib 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" ); } } } contract VoxVaultV2 is ERC20Lib, ReentrancyGuard { using SafeERC20Lib for IERC20Lib; using Address for address; using SafeMath for uint256; IERC20Lib internal token; IERC20Lib internal vox; address public underlying; uint256 public min = 9500; uint256 public constant max = 10000; uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 15; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; bool public isActive = false; address public governance; address public treasury; address public timelock; address public strategy; address public burn = 0x000000000000000000000000000000000000dEaD; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor( address _underlying, address _vox, address _governance, address _treasury, address _timelock ) public ERC20Lib( string(abi.encodePacked("voxie ", ERC20Lib(_underlying).name())), string(abi.encodePacked("v", ERC20Lib(_underlying).symbol())) ) { require( address(_underlying) != address(_vox), "!underlying equal to vox"); _setupDecimals(ERC20Lib(_underlying).decimals()); token = IERC20Lib(_underlying); vox = IERC20Lib(_vox); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(31250000000000000); multiplierCosts.push(125000000000000000); multiplierCosts.push(281250000000000000); multiplierCosts.push(500000000000000000); multiplierCosts.push(781250000000000000); } // **** Modifiers **** // modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) public isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "numerator cannot be greater than denominator"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) public isGovernance { governance = _governance; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) public isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) public isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'burn max'); require(_burnFee >= burnFeeMin, 'burn min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max withdrawal fee"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'vault is not active'); require(strategy != address(0), 'strategy is not set'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "!no contract"); require(isActive, 'vault is not active'); require(strategy != address(0), 'strategy is not yet set'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].add(tierBase); shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].add(tierBase); shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "!no contract"); require(block.number > depositBlocks[msg.sender], 'withdraw: not the same block as deposits'); require(_amount > 0, 'withdraw: positive amount'); require(_amount <= deposits[msg.sender], 'withdraw: more than deposited'); require(issued[msg.sender] > 0, 'withdraw: you need to first make a deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "withdraw: not enough shares in balance"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { return (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, 'vault is not active'); require(strategy != address(0), 'strategy is not yet set'); require(_tiers > 0, 'you need to purchase at least one multiplier'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, 'you can not purchase so many tiers'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20Lib(vox).balanceOf(msg.sender) >= totalCost, 'you do not have enough VOX to purchase the multiplier tiers'); vox.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the VOX tokens collected by the multiplier purchases function distribute() external isGovernance { uint256 b = vox.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); vox.safeTransfer(burn, toBurn); vox.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to the treasury function salvage(address reserve, uint256 amount) external { require(msg.sender == governance, "!governance"); require(reserve != address(token), "token"); require(reserve != address(vox), "vox"); IERC20Lib(reserve).safeTransfer(treasury, amount); } // Helper function when migrating to new version function setMultiplier(address account, uint256 multiplier) external isGovernance { require(multiplier <= multiplierCosts.length, 'multiplier value too high'); tiers[account] = multiplier; } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, 'all tiers have already been purchased'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } }
Helper function when migrating to new version
function setMultiplier(address account, uint256 multiplier) external isGovernance { require(multiplier <= multiplierCosts.length, 'multiplier value too high'); tiers[account] = multiplier; }
1,464
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./libraries/external/QueryAccount.sol"; import "solidity-bytes-utils/contracts/BytesLib.sol"; import "@pythnetwork/pyth-sdk-solidity/PythStructs.sol"; /// @title Consume prices from the Pyth Network (https://pyth.network/). /// @dev Please refer to the guidance at https://docs.pyth.network/consumers/best-practices for how to consume prices safely. /// @author Pyth Data Association contract Pyth { using BytesLib for bytes; /// @notice Returns the current price and confidence interval. /// @dev Reverts if the current price is not available. /// @param id The Pyth Price Feed ID of which to fetch the current price and confidence interval. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getCurrentPrice(bytes32 id) external returns (PythStructs.Price memory price) { PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id); require(priceFeed.status == PythStructs.PriceStatus.TRADING, "current price unavailable"); price.price = priceFeed.price; price.conf = priceFeed.conf; price.expo = priceFeed.expo; return price; } /// @notice Returns the exponential moving average price and confidence interval. /// @dev Reverts if the current exponential moving average price is not available. /// @param id The Pyth Price Feed ID of which to fetch the current price and confidence interval. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getEmaPrice(bytes32 id) external returns (PythStructs.Price memory price) { PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id); price.price = priceFeed.emaPrice; price.conf = priceFeed.emaConf; price.expo = priceFeed.expo; return price; } /// @notice Returns the most recent previous price with a status of Trading, with the time when this was published. /// @dev This may be a price from arbitrarily far in the past: it is important that you check the publish time before using the price. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. /// @return publishTime - the UNIX timestamp of when this price was computed. function getPrevPriceUnsafe(bytes32 id) external returns (PythStructs.Price memory price, uint64 publishTime) { PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id); price.price = priceFeed.prevPrice; price.conf = priceFeed.prevConf; price.expo = priceFeed.expo; return (price, priceFeed.prevPublishTime); } function queryPriceFeed(bytes32 id) public returns (PythStructs.PriceFeed memory) { uint64 priceAccountDataLen = 244; uint256 addr = uint256(id); require(QueryAccount.cache(addr, 0, priceAccountDataLen), "failed to update cache"); (bool success, bytes memory accData) = QueryAccount.data(addr, 0, priceAccountDataLen); require(success, "failed to query account data"); return parseSolanaPriceAccountData(id, accData); } function parseSolanaPriceAccountData(bytes32 id, bytes memory data) public pure returns (PythStructs.PriceFeed memory priceFeed) { priceFeed.id = id; uint256 offset = 0; // Skip: magic (4) + ver (4) + atype (4) + size (4) + ptype (4) offset += 20; priceFeed.expo = readLittleEndianSigned32(data.toUint32(offset)); offset += 4; priceFeed.maxNumPublishers = readLittleEndianUnsigned32(data.toUint32(offset)); offset += 4; priceFeed.numPublishers = readLittleEndianUnsigned32(data.toUint32(offset)); offset += 4; // Skip: last_slot (8) + valid_slot (8) offset += 16; priceFeed.emaPrice = readLittleEndianSigned64(data.toUint64(offset)); offset += 8; // Skip: twap.numer_ (8) + twap.denom_ (8) offset += 16; priceFeed.emaConf = readLittleEndianUnsigned64(data.toUint64(offset)); offset += 8; // Skip: twac.numer_ (8) + twac.denom_ (8) offset += 16; priceFeed.publishTime = readLittleEndianUnsigned64(data.toUint64(offset)); offset += 8; // Skip: min_pub (1) + drv2_ (1) + drv3_ (2) + drv4_ (4) offset += 8; priceFeed.productId = bytes32(data.slice(offset, 32)); offset += 32; // Skip: next_ (32) + prev_slot_ (8) offset += 40; priceFeed.prevPrice = readLittleEndianSigned64(data.toUint64(offset)); offset += 8; priceFeed.prevConf = readLittleEndianUnsigned64(data.toUint64(offset)); offset += 8; priceFeed.prevPublishTime = readLittleEndianUnsigned64(data.toUint64(offset)); offset += 8; priceFeed.price = readLittleEndianSigned64(data.toUint64(offset)); offset += 8; priceFeed.conf = readLittleEndianUnsigned64(data.toUint64(offset)); offset += 8; priceFeed.status = PythStructs.PriceStatus(readLittleEndianUnsigned32(data.toUint32(offset))); } // Little Endian helpers function readLittleEndianSigned64(uint64 input) internal pure returns (int64) { uint64 val = input; val = ((val << 8) & 0xFF00FF00FF00FF00) | ((val >> 8) & 0x00FF00FF00FF00FF); val = ((val << 16) & 0xFFFF0000FFFF0000) | ((val >> 16) & 0x0000FFFF0000FFFF); return int64((val << 32) | ((val >> 32) & 0xFFFFFFFF)); } function readLittleEndianUnsigned64(uint64 input) internal pure returns (uint64 val) { val = input; val = ((val << 8) & 0xFF00FF00FF00FF00) | ((val >> 8) & 0x00FF00FF00FF00FF); val = ((val << 16) & 0xFFFF0000FFFF0000) | ((val >> 16) & 0x0000FFFF0000FFFF); val = (val << 32) | (val >> 32); } function readLittleEndianSigned32(uint32 input) internal pure returns (int32) { uint32 val = input; val = ((val & 0xFF00FF00) >> 8) | ((val & 0x00FF00FF) << 8); return int32((val << 16) | ((val >> 16) & 0xFFFF)); } function readLittleEndianUnsigned32(uint32 input) internal pure returns (uint32 val) { val = input; val = ((val & 0xFF00FF00) >> 8) | ((val & 0x00FF00FF) << 8); val = (val << 16) | (val >> 16); } }
Skip: magic (4) + ver (4) + atype (4) + size (4) + ptype (4) Skip: last_slot (8) + valid_slot (8) Skip: twap.numer_ (8) + twap.denom_ (8) Skip: twac.numer_ (8) + twac.denom_ (8) Skip: min_pub (1) + drv2_ (1) + drv3_ (2) + drv4_ (4) Skip: next_ (32) + prev_slot_ (8)
function parseSolanaPriceAccountData(bytes32 id, bytes memory data) public pure returns (PythStructs.PriceFeed memory priceFeed) { priceFeed.id = id; uint256 offset = 0; offset += 20; priceFeed.expo = readLittleEndianSigned32(data.toUint32(offset)); offset += 4; priceFeed.maxNumPublishers = readLittleEndianUnsigned32(data.toUint32(offset)); offset += 4; priceFeed.numPublishers = readLittleEndianUnsigned32(data.toUint32(offset)); offset += 4; offset += 16; priceFeed.emaPrice = readLittleEndianSigned64(data.toUint64(offset)); offset += 8; offset += 16; priceFeed.emaConf = readLittleEndianUnsigned64(data.toUint64(offset)); offset += 8; offset += 16; priceFeed.publishTime = readLittleEndianUnsigned64(data.toUint64(offset)); offset += 8; offset += 8; priceFeed.productId = bytes32(data.slice(offset, 32)); offset += 32; offset += 40; priceFeed.prevPrice = readLittleEndianSigned64(data.toUint64(offset)); offset += 8; priceFeed.prevConf = readLittleEndianUnsigned64(data.toUint64(offset)); offset += 8; priceFeed.prevPublishTime = readLittleEndianUnsigned64(data.toUint64(offset)); offset += 8; priceFeed.price = readLittleEndianSigned64(data.toUint64(offset)); offset += 8; priceFeed.conf = readLittleEndianUnsigned64(data.toUint64(offset)); offset += 8; priceFeed.status = PythStructs.PriceStatus(readLittleEndianUnsigned32(data.toUint32(offset))); }
14,036,714
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./MagicLampWalletBase.sol"; import "./MagicLampWalletEvents.sol"; import "./IERC721Receiver.sol"; import "./IERC1155Receiver.sol"; import "./ERC165.sol"; import "./IERC20.sol"; import "./IERC721.sol"; import "./IERC1155.sol"; contract MagicLampWallet is MagicLampWalletBase, MagicLampWalletEvents, ERC165, IERC1155Receiver, IERC721Receiver { using SafeMath for uint256; function tokenTypeERC20() external pure returns (uint8) { return _TOKEN_TYPE_ERC20; } function tokenTypeERC721() external pure returns (uint8) { return _TOKEN_TYPE_ERC721; } function tokenTypeERC1155() external pure returns (uint8) { return _TOKEN_TYPE_ERC1155; } /** * @dev Checks if magicLamp has been locked. */ function isLocked(address host, uint256 id) external view returns (bool locked, uint256 endTime) { if (_lockedTimestamps[host][id] <= block.timestamp) { locked = false; } else { locked = true; endTime = _lockedTimestamps[host][id] - 1; } } /** * @dev Gets token counts inside wallet, including ETH */ function getTokensCount(address host, uint256 id) public view returns (uint256 ethCount, uint256 erc20Count, uint256 erc721Count, uint256 erc1155Count) { if (_ethBalances[host][id] > 0) { ethCount = 1; } Token[] memory tokens = _tokens[host][id]; for (uint256 i = 0; i < tokens.length; i++) { Token memory token = tokens[i]; if (token.tokenType == _TOKEN_TYPE_ERC20) { erc20Count++; } else if (token.tokenType == _TOKEN_TYPE_ERC721) { erc721Count++; } else if (token.tokenType == _TOKEN_TYPE_ERC1155) { erc1155Count++; } } } /** * @dev Gets tokens for wallet */ function getTokens(address host, uint256 id) external view returns (uint8[] memory tokenTypes, address[] memory tokenAddresses) { Token[] memory tokens = _tokens[host][id]; tokenTypes = new uint8[](tokens.length); tokenAddresses = new address[](tokens.length); for (uint256 i; i < tokens.length; i++) { tokenTypes[i] = tokens[i].tokenType; tokenAddresses[i] = tokens[i].tokenAddress; } } /** * @dev Supports host(ERC721 token address) for wallet features */ function support(address host) external onlyOwner { require(!walletFeatureHosted[host], "MagicLampWallet::support: already supported"); walletFeatureHosts.push(host); walletFeatureHosted[host] = true; emit MagicLampWalletSupported(host); } /** * @dev Unsupports host(ERC721 token address) for wallet features */ function unsupport(address host) external onlyOwner { require(walletFeatureHosted[host], "MagicLampWallet::unsupport: not found"); for (uint256 i = 0; i < walletFeatureHosts.length; i++) { if (walletFeatureHosts[i] == host) { walletFeatureHosts[i] = walletFeatureHosts[walletFeatureHosts.length - 1]; walletFeatureHosts.pop(); delete walletFeatureHosted[host]; emit MagicLampWalletUnsupported(host); break; } } } /** * @dev Gets */ function isSupported(address host) external view returns(bool) { return walletFeatureHosted[host]; } /** * @dev Sets MagicLamp Swap contract */ function setMagicLampSwap(address newAddress) external onlyOwner { address priviousAddress = magicLampSwap; require(priviousAddress != newAddress, "MagicLampWallet::setMagicLampSwap: same address"); magicLampSwap = newAddress; emit MagicLampWalletSwapChanged(priviousAddress, newAddress); } /** * @dev Locks wallet */ function lock(address host, uint256 id, uint256 timeInSeconds) external { _onlyWalletOwner(host, id); // _unlocked(host, id); _lockedTimestamps[host][id] = block.timestamp.add(timeInSeconds); emit MagicLampWalletLocked(_msgSender(), host, id, block.timestamp, _lockedTimestamps[host][id]); } /** * @dev Checks if token exists inside wallet */ function existsERC721ERC1155(address host, uint256 id, address token, uint256 tokenId) public view returns (bool) { uint256[] memory ids = _erc721ERC1155TokenIds[host][id][token]; for (uint256 i = 0; i < ids.length; i++) { if (ids[i] == tokenId) { return true; } } return false; } /** * @dev Gets ETH balance */ function getETH(address host, uint256 id) public view returns (uint256 balance) { _exists(host, id); balance = _ethBalances[host][id]; } /** * @dev Deposits ETH tokens into wallet */ function depositETH(address host, uint256 id, uint256 amount) external payable { _exists(host, id); require(amount > 0 && amount == msg.value, "MagicLampWallet::depositETH: invalid amount"); _ethBalances[host][id] = _ethBalances[host][id].add(msg.value); emit MagicLampWalletETHDeposited(_msgSender(), host, id, msg.value); } /** * @dev Withdraws ETH tokens from wallet */ function withdrawETH(address host, uint256 id, uint256 amount) public payable { _onlyWalletOwner(host, id); _unlocked(host, id); require(amount > 0 && amount <= address(this).balance); require(amount <= getETH(host, id)); address to = IERC721(host).ownerOf(id); payable(to).transfer(amount); _ethBalances[host][id] = _ethBalances[host][id].sub(amount); emit MagicLampWalletETHWithdrawn(_msgSender(), host, id, amount, to); } /** * @dev Transfers ETH tokens from wallet into another wallet */ function transferETH(address fromHost, uint256 fromId, uint256 amount, address toHost, uint256 toId) public { _onlyWalletOwner(fromHost, fromId); _unlocked(fromHost, fromId); _exists(toHost, toId); require(fromHost != toHost || fromId != toId, "MagicLampWallet::transferETH: same wallet"); _ethBalances[fromHost][fromId] = _ethBalances[fromHost][fromId].sub(amount); _ethBalances[toHost][toId] = _ethBalances[toHost][toId].add(amount); emit MagicLampWalletETHTransferred(_msgSender(), fromHost, fromId, amount, toHost, toId); } /** * @dev Gets ERC20 token info */ function getERC20Tokens(address host, uint256 id) public view returns (address[] memory addresses, uint256[] memory tokenBalances) { Token[] memory tokens = _tokens[host][id]; (, uint256 erc20Count, , ) = getTokensCount(host, id); addresses = new address[](erc20Count); tokenBalances = new uint256[](erc20Count); uint256 j = 0; for (uint256 i = 0; i < tokens.length; i++) { Token memory token = tokens[i]; if (token.tokenType == _TOKEN_TYPE_ERC20) { addresses[j] = token.tokenAddress; tokenBalances[j] = _erc20TokenBalances[host][id][token.tokenAddress]; j++; } } } /** * @dev Gets ERC721 token info */ function getERC721Tokens(address host, uint256 id) public view returns (address[] memory addresses, uint256[] memory tokenBalances) { Token[] memory tokens = _tokens[host][id]; (,, uint256 erc721Count, ) = getTokensCount(host, id); addresses = new address[](erc721Count); tokenBalances = new uint256[](erc721Count); uint256 j = 0; for (uint256 i = 0; i < tokens.length; i++) { Token memory token = tokens[i]; if (token.tokenType == _TOKEN_TYPE_ERC721) { addresses[j] = token.tokenAddress; tokenBalances[j] = _erc721ERC1155TokenIds[host][id][token.tokenAddress].length; j++; } } } /** * @dev Gets ERC721 or ERC1155 IDs */ function getERC721ERC1155IDs(address host, uint256 id, address token) public view returns (uint256[] memory) { return _erc721ERC1155TokenIds[host][id][token]; } /** * @dev Gets ERC1155 token addresses info */ function getERC1155Tokens(address host, uint256 id) public view returns (address[] memory addresses) { Token[] memory tokens = _tokens[host][id]; (,,, uint256 erc1155Count) = getTokensCount(host, id); addresses = new address[](erc1155Count); uint256 j = 0; for (uint256 i = 0; i < tokens.length; i++) { Token memory token = tokens[i]; if (token.tokenType == _TOKEN_TYPE_ERC1155) { addresses[j] = token.tokenAddress; j++; } } } /** * @dev Gets ERC1155 token balances by IDs */ function getERC1155TokenBalances(address host, uint256 id, address token, uint256[] memory tokenIds) public view returns (uint256[] memory tokenBalances) { tokenBalances = new uint256[](tokenIds.length); for (uint256 i = 0; i < tokenIds.length; i++) { tokenBalances[i] = _erc1155TokenBalances[host][id][token][tokenIds[i]]; } } /** * @dev Deposits ERC20 tokens into wallet. */ function depositERC20(address host, uint256 id, address[] memory tokens, uint256[] memory amounts) external { _exists(host, id); require(tokens.length > 0 && tokens.length == amounts.length, "MagicLampWallet::depositERC20: invalid parameters"); for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); uint256 prevBalance = token.balanceOf(address(this)); token.transferFrom(_msgSender(), address(this), amounts[i]); uint256 receivedAmount = token.balanceOf(address(this)).sub(prevBalance); _addERC20TokenBalance(host, id, tokens[i], receivedAmount); emit MagicLampWalletERC20Deposited(_msgSender(), host, id, tokens[i], receivedAmount); } } /** * @dev Withdraws ERC20 tokens from wallet. */ function withdrawERC20(address host, uint256 id, address[] memory tokens, uint256[] memory amounts) public { _onlyWalletOwner(host, id); _unlocked(host, id); require(tokens.length > 0 && tokens.length == amounts.length, "MagicLampWallet::withdrawERC20: invalid parameters"); address to = IERC721(host).ownerOf(id); for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); token.transfer(to, amounts[i]); _subERC20TokenBalance(host, id, tokens[i], amounts[i]); emit MagicLampWalletERC20Withdrawn(_msgSender(), host, id, tokens[i], amounts[i], to); } } /** * @dev Transfers ERC20 tokens from wallet into another wallet. */ function transferERC20(address fromHost, uint256 fromId, address token, uint256 amount, address toHost, uint256 toId) public { _onlyWalletOwner(fromHost, fromId); _unlocked(fromHost, fromId); _exists(toHost, toId); require(fromHost != toHost || fromId != toId, "MagicLampWallet::transferERC20: same wallet"); _subERC20TokenBalance(fromHost, fromId, token, amount); _addERC20TokenBalance(toHost, toId, token, amount); emit MagicLampWalletERC20Transferred(_msgSender(), fromHost, fromId, token, amount, toHost, toId); } /** * @dev Deposits ERC721 tokens into wallet. */ function depositERC721(address host, uint256 id, address token, uint256[] memory tokenIds) external { _exists(host, id); IERC721 iToken = IERC721(token); for (uint256 i = 0; i < tokenIds.length; i++) { require(token != host || tokenIds[i] != id, "MagicLampWallet::depositERC721: self deposit"); iToken.safeTransferFrom(_msgSender(), address(this), tokenIds[i]); _putTokenId(host, id, _TOKEN_TYPE_ERC721, token, tokenIds[i]); emit MagicLampWalletERC721Deposited(_msgSender(), host, id, token, tokenIds[i]); } } /** * @dev Withdraws ERC721 token from wallet. */ function withdrawERC721(address host, uint256 id, address token, uint256[] memory tokenIds) public { _onlyWalletOwner(host, id); _unlocked(host, id); IERC721 iToken = IERC721(token); address to = IERC721(host).ownerOf(id); for (uint256 i = 0; i < tokenIds.length; i++) { require(iToken.ownerOf(tokenIds[i]) == address(this)); iToken.safeTransferFrom(address(this), to, tokenIds[i]); _popTokenId(host, id, _TOKEN_TYPE_ERC721, token, tokenIds[i]); emit MagicLampWalletERC721Withdrawn(_msgSender(), host, id, token, tokenIds[i], to); } } /** * @dev Transfers ERC721 tokens from wallet to another wallet. */ function transferERC721(address fromHost, uint256 fromId, address token, uint256[] memory tokenIds, address toHost, uint256 toId) public { _onlyWalletOwner(fromHost, fromId); _unlocked(fromHost, fromId); _exists(toHost, toId); require(fromHost != toHost || fromId != toId, "MagicLampWallet::transferERC721: same wallet"); for (uint256 i = 0; i < tokenIds.length; i++) { _popTokenId(fromHost, fromId, _TOKEN_TYPE_ERC721, token, tokenIds[i]); _putTokenId(toHost, toId, _TOKEN_TYPE_ERC721, token, tokenIds[i]); emit MagicLampWalletERC721Transferred(_msgSender(), fromHost, fromId, token, tokenIds[i], toHost, toId); } } /** * @dev Deposits ERC1155 token into wallet. */ function depositERC1155(address host, uint256 id, address token, uint256[] memory tokenIds, uint256[] memory amounts) external { _exists(host, id); IERC1155 iToken = IERC1155(token); for (uint256 i = 0; i < tokenIds.length; i++) { iToken.safeTransferFrom(_msgSender(), address(this), tokenIds[i], amounts[i], bytes("")); _addERC1155TokenBalance(host, id, token, tokenIds[i], amounts[i]); emit MagicLampWalletERC1155Deposited(_msgSender(), host, id, token, tokenIds[i], amounts[i]); } } /** * @dev Withdraws ERC1155 token from wallet. */ function withdrawERC1155(address host, uint256 id, address token, uint256[] memory tokenIds, uint256[] memory amounts) public { _onlyWalletOwner(host, id); _unlocked(host, id); IERC1155 iToken = IERC1155(token); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; uint256 amount = amounts[i]; address to = IERC721(host).ownerOf(id); iToken.safeTransferFrom(address(this), to, tokenId, amount, bytes("")); _subERC1155TokenBalance(host, id, token, tokenId, amount); emit MagicLampWalletERC1155Withdrawn(_msgSender(), host, id, token, tokenId, amount, to); } } /** * @dev Transfers ERC1155 token from wallet to another wallet. */ function transferERC1155(address fromHost, uint256 fromId, address token, uint256[] memory tokenIds, uint256[] memory amounts, address toHost, uint256 toId) public { _onlyWalletOwner(fromHost, fromId); _unlocked(fromHost, fromId); require(fromHost != toHost || fromId != toId, "MagicLampWallet::transferERC1155: same wallet"); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; uint256 amount = amounts[i]; _subERC1155TokenBalance(fromHost, fromId, token, tokenId, amount); _addERC1155TokenBalance(toHost, toId, token, tokenId, amount); emit MagicLampWalletERC1155Transferred(_msgSender(), fromHost, fromId, token, tokenId, amount, toHost, toId); } } /** * @dev Withdraws all of tokens from wallet. */ function withdrawAll(address host, uint256 id) external { uint256 eth = getETH(host, id); if (eth > 0) { withdrawETH(host, id, eth); } (address[] memory erc20Addresses, uint256[] memory erc20Balances) = getERC20Tokens(host, id); if (erc20Addresses.length > 0) { withdrawERC20(host, id, erc20Addresses, erc20Balances); } (address[] memory erc721Addresses, ) = getERC721Tokens(host, id); for (uint256 a = 0; a < erc721Addresses.length; a++) { uint256[] memory ids = _erc721ERC1155TokenIds[host][id][erc721Addresses[a]]; withdrawERC721(host, id, erc721Addresses[a], ids); } address[] memory erc1155Addresses = getERC1155Tokens(host, id); for (uint256 a = 0; a < erc1155Addresses.length; a++) { uint256[] memory ids = _erc721ERC1155TokenIds[host][id][erc1155Addresses[a]]; uint256[] memory tokenBalances = getERC1155TokenBalances(host, id, erc1155Addresses[a], ids); withdrawERC1155(host, id, erc1155Addresses[a], ids, tokenBalances); } } /** * @dev Transfers all of tokens to another wallet. */ function transferAll(address fromHost, uint256 fromId, address toHost, uint256 toId) external { { uint256 eth = getETH(fromHost, fromId); if (eth > 0) { transferETH(fromHost, fromId, eth, toHost, toId); } } { (address[] memory erc20Addresses, uint256[] memory erc20Balances ) = getERC20Tokens(fromHost, fromId); for(uint256 i = 0; i < erc20Addresses.length; i++){ transferERC20(fromHost, fromId, erc20Addresses[i], erc20Balances[i], toHost, toId); } } { (address[] memory erc721Addresses, ) = getERC721Tokens(fromHost, fromId); for (uint256 a = 0; a < erc721Addresses.length; a++) { uint256[] memory ids = getERC721ERC1155IDs(fromHost, fromId, erc721Addresses[a]); transferERC721(fromHost, fromId, erc721Addresses[a], ids, toHost, toId); } } { address[] memory erc1155Addresses = getERC1155Tokens(fromHost, fromId); for (uint256 a = 0; a < erc1155Addresses.length; a++) { uint256[] memory ids = getERC721ERC1155IDs(fromHost, fromId, erc1155Addresses[a]); uint256[] memory tokenBalances = getERC1155TokenBalances(fromHost, fromId, erc1155Addresses[a], ids); transferERC1155(fromHost, fromId, erc1155Addresses[a], ids, tokenBalances, toHost, toId); } } } function onERC721Received(address, address, uint256, bytes calldata) external pure override returns (bytes4) { return this.onERC721Received.selector; } function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure override returns (bytes4) { return 0xf23a6e61; } function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata) external pure override returns (bytes4) { return 0xbc197c81; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./SafeMath.sol"; import "./IERC721.sol"; import "./Ownable.sol"; import "./MagicLampWalletStorage.sol"; contract MagicLampWalletBase is MagicLampWalletStorage, Ownable { using SafeMath for uint256; function _onlyWalletOwner(address host, uint256 id) internal view { require(walletFeatureHosted[host], "Unsupported host"); require( IERC721(host).ownerOf(id) == _msgSender(), "Only wallet owner can call" ); } function _exists(address host, uint256 id) internal view { require(walletFeatureHosted[host], "Unsupported host"); require(IERC721(host).ownerOf(id) != address(0), "NFT does not exist"); } function _unlocked(address host, uint256 id) internal view { require(_lockedTimestamps[host][id] <= block.timestamp, "Wallet is locked"); } function _onlyWalletOwnerOrHost(address host, uint256 id) internal view { require(walletFeatureHosted[host], "Unsupported host"); require( IERC721(host).ownerOf(id) == _msgSender() || host == _msgSender(), "Only wallet owner or host can call" ); } /** * @dev Puts token(type, address) */ function _putToken(address host, uint256 id, uint8 tokenType, address token) internal { Token[] storage tokens = _tokens[host][id]; uint256 i = 0; for (; i < tokens.length && (tokens[i].tokenType != tokenType || tokens[i].tokenAddress != token); i++) { } if (i == tokens.length) { tokens.push(Token({tokenType: tokenType, tokenAddress: token})); } } /** * @dev Pops token(type, address) */ function _popToken(address host, uint256 id, uint8 tokenType, address token) internal { Token[] storage tokens = _tokens[host][id]; for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i].tokenType == tokenType && tokens[i].tokenAddress == token) { tokens[i] = tokens[tokens.length - 1]; tokens.pop(); if (tokens.length == 0) { delete _tokens[host][id]; } return; } } require(false, "Not found token"); } /** * @dev Puts a token id */ function _putTokenId(address host, uint256 id, uint8 tokenType, address token, uint256 tokenId) internal { if (_erc721ERC1155TokenIds[host][id][token].length == 0) { _putToken(host, id, tokenType, token); } _erc721ERC1155TokenIds[host][id][token].push(tokenId); } /** * @dev Pops a token id */ function _popTokenId(address host, uint256 id, uint8 tokenType, address token, uint256 tokenId) internal { uint256[] storage ids = _erc721ERC1155TokenIds[host][id][token]; for (uint256 i = 0; i < ids.length; i++) { if (ids[i] == tokenId) { ids[i] = ids[ids.length - 1]; ids.pop(); if (ids.length == 0) { delete _erc721ERC1155TokenIds[host][id][token]; _popToken(host, id, tokenType, token); } return; } } require(false, "Not found token id"); } /** * @dev Adds token balance */ function _addERC20TokenBalance(address host, uint256 id, address token, uint256 amount) internal { if (amount == 0) return; if (_erc20TokenBalances[host][id][token] == 0) { _putToken(host, id, _TOKEN_TYPE_ERC20, token); } _erc20TokenBalances[host][id][token] = _erc20TokenBalances[host][id][token].add(amount); } /** * @dev Subs token balance */ function _subERC20TokenBalance(address host, uint256 id, address token, uint256 amount) internal { if (amount == 0) return; _erc20TokenBalances[host][id][token] = _erc20TokenBalances[host][id][token].sub(amount); if (_erc20TokenBalances[host][id][token] == 0) { _popToken(host, id, _TOKEN_TYPE_ERC20, token); } } /** * @dev Adds ERC1155 token balance */ function _addERC1155TokenBalance(address host, uint256 id, address token, uint256 tokenId, uint256 amount) internal { if (amount == 0) return; if (_erc1155TokenBalances[host][id][token][tokenId] == 0) { _putTokenId(host, id, _TOKEN_TYPE_ERC1155, token, tokenId); } _erc1155TokenBalances[host][id][token][tokenId] = _erc1155TokenBalances[host][id][token][tokenId].add(amount); } /** * @dev Subs ERC1155 token balance */ function _subERC1155TokenBalance(address host, uint256 id, address token, uint256 tokenId, uint256 amount) internal { if (amount == 0) return; _erc1155TokenBalances[host][id][token][tokenId] = _erc1155TokenBalances[host][id][token][tokenId].sub(amount); if (_erc1155TokenBalances[host][id][token][tokenId] == 0) { _popTokenId(host, id, _TOKEN_TYPE_ERC1155, token, tokenId); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract MagicLampWalletEvents { event MagicLampWalletSupported( address indexed host ); event MagicLampWalletUnsupported( address indexed host ); event MagicLampWalletSwapChanged( address indexed previousMagicLampSwap, address indexed newMagicLampSwap ); event MagicLampWalletLocked( address indexed owner, address indexed host, uint256 id, uint256 startTimestamp, uint256 endTimestamp ); event MagicLampWalletOpened( address indexed owner, address indexed host, uint256 id ); event MagicLampWalletClosed( address indexed owner, address indexed host, uint256 id ); event MagicLampWalletETHDeposited( address indexed owner, address indexed host, uint256 id, uint256 amount ); event MagicLampWalletETHWithdrawn( address indexed owner, address indexed host, uint256 id, uint256 amount, address to ); event MagicLampWalletETHTransferred( address indexed owner, address indexed host, uint256 id, uint256 amount, address indexed toHost, uint256 toId ); event MagicLampWalletERC20Deposited( address indexed owner, address indexed host, uint256 id, address erc20Token, uint256 amount ); event MagicLampWalletERC20Withdrawn( address indexed owner, address indexed host, uint256 id, address erc20Token, uint256 amount, address to ); event MagicLampWalletERC20Transferred( address indexed owner, address indexed host, uint256 id, address erc20Token, uint256 amount, address indexed toHost, uint256 toId ); event MagicLampWalletERC721Deposited( address indexed owner, address indexed host, uint256 id, address erc721Token, uint256 erc721TokenId ); event MagicLampWalletERC721Withdrawn( address indexed owner, address indexed host, uint256 id, address erc721Token, uint256 erc721TokenId, address to ); event MagicLampWalletERC721Transferred( address indexed owner, address indexed host, uint256 id, address erc721Token, uint256 erc721TokenId, address indexed toHost, uint256 toId ); event MagicLampWalletERC1155Deposited( address indexed owner, address indexed host, uint256 id, address erc1155Token, uint256 erc1155TokenId, uint256 amount ); event MagicLampWalletERC1155Withdrawn( address indexed owner, address indexed host, uint256 id, address erc1155Token, uint256 erc1155TokenId, uint256 amount, address indexed to ); event MagicLampWalletERC1155Transferred( address indexed owner, address indexed host, uint256 id, address erc1155Token, uint256 erc1155TokenId, uint256 amount, address indexed toHost, uint256 toId ); event MagicLampWalletERC20Swapped( address indexed owner, address indexed host, uint256 id, address inToken, uint256 inAmount, address outToken, uint256 outAmount, address indexed to ); event MagicLampWalletERC721Swapped( address indexed owner, address indexed host, uint256 id, address inToken, uint256 inTokenId, address outToken, uint256 outTokenId, address indexed to ); event MagicLampWalletERC1155Swapped( address indexed owner, address indexed host, uint256 id, address inToken, uint256 inTokenId, uint256 inAmount, address outToken, uint256 outTokenId, uint256 outTokenAmount, address indexed to ); } // 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 "./IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ 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.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 custom add */ function burn(uint256 burnQuantity) 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 "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; // File: @openzeppelin/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; address private _authorizedNewOwner; event OwnershipTransferAuthorization(address indexed authorizedAddress); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Returns the address of the current authorized new owner. */ function authorizedNewOwner() public view virtual returns (address) { return _authorizedNewOwner; } /** * @notice Authorizes the transfer of ownership from _owner to the provided address. * NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ). * This authorization may be removed by another call to this function authorizing * the null address. * * @param authorizedAddress The address authorized to become the new owner. */ function authorizeOwnershipTransfer(address authorizedAddress) external onlyOwner { _authorizedNewOwner = authorizedAddress; emit OwnershipTransferAuthorization(_authorizedNewOwner); } /** * @notice Transfers ownership of this contract to the _authorizedNewOwner. */ function assumeOwnership() external { require(_msgSender() == _authorizedNewOwner, "Ownable: only the authorized new owner can accept ownership"); emit OwnershipTransferred(_owner, _authorizedNewOwner); _owner = _authorizedNewOwner; _authorizedNewOwner = address(0); } /** * @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. * * @param confirmAddress The address wants to give up ownership. */ function renounceOwnership(address confirmAddress) public virtual onlyOwner { require(confirmAddress == _owner, "Ownable: confirm address is wrong"); emit OwnershipTransferred(_owner, address(0)); _authorizedNewOwner = address(0); _owner = address(0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract MagicLampWalletStorage { struct Token { uint8 tokenType; // TOKEN_TYPE address tokenAddress; } // Token types uint8 internal constant _TOKEN_TYPE_ERC20 = 1; uint8 internal constant _TOKEN_TYPE_ERC721 = 2; uint8 internal constant _TOKEN_TYPE_ERC1155 = 3; // Mapping from Host -> ID -> Token(ERC721 or ERC1155) -> IDs mapping(address => mapping(uint256 => mapping(address => uint256[]))) internal _erc721ERC1155TokenIds; // Mapping from Host -> ID -> Token(ERC20) -> Balance mapping(address => mapping(uint256 => mapping(address => uint256))) internal _erc20TokenBalances; // Mapping from Host -> ID -> Token(ERC1155) -> Token ID -> Balance mapping(address => mapping(uint256 => mapping(address => mapping(uint256 => uint256)))) internal _erc1155TokenBalances; // Mapping from Host -> ID -> Token(ETH) -> Balance mapping(address => mapping(uint256 => uint256)) internal _ethBalances; address public magicLampSwap; // List of ERC721 tokens which wallet features get supported address[] public walletFeatureHosts; // Mapping from Host -> bool mapping(address => bool) public walletFeatureHosted; // Mapping from Host -> ID -> Tokens mapping(address => mapping(uint256 => Token[])) internal _tokens; // Mapping from Host -> ID -> Locked Time mapping(address => mapping(uint256 => uint256)) internal _lockedTimestamps; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev 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; } }
Transfers all of tokens to another wallet./
function transferAll(address fromHost, uint256 fromId, address toHost, uint256 toId) external { { uint256 eth = getETH(fromHost, fromId); if (eth > 0) { transferETH(fromHost, fromId, eth, toHost, toId); } } { (address[] memory erc20Addresses, uint256[] memory erc20Balances ) = getERC20Tokens(fromHost, fromId); for(uint256 i = 0; i < erc20Addresses.length; i++){ transferERC20(fromHost, fromId, erc20Addresses[i], erc20Balances[i], toHost, toId); } } { (address[] memory erc721Addresses, ) = getERC721Tokens(fromHost, fromId); for (uint256 a = 0; a < erc721Addresses.length; a++) { uint256[] memory ids = getERC721ERC1155IDs(fromHost, fromId, erc721Addresses[a]); transferERC721(fromHost, fromId, erc721Addresses[a], ids, toHost, toId); } } { address[] memory erc1155Addresses = getERC1155Tokens(fromHost, fromId); for (uint256 a = 0; a < erc1155Addresses.length; a++) { uint256[] memory ids = getERC721ERC1155IDs(fromHost, fromId, erc1155Addresses[a]); uint256[] memory tokenBalances = getERC1155TokenBalances(fromHost, fromId, erc1155Addresses[a], ids); transferERC1155(fromHost, fromId, erc1155Addresses[a], ids, tokenBalances, toHost, toId); } } }
252,753
// Sources flattened with hardhat v2.9.3 https://hardhat.org // File @openzeppelin/contracts/utils/introspection/[email protected] // 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); } // File @openzeppelin/contracts/token/ERC1155/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC1155/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: 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. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC1155/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/access/[email protected] // 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 contracts/katana.sol pragma solidity ^0.8.0; library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function initialize(Counter storage counter, uint256 _value) internal { counter._value = _value; } function reset(Counter storage counter) internal { counter._value = 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 These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } interface Shiburai { function balanceOf(address account) external view returns (uint256); } interface Kimono { function onMintingWithKimono(address _samurai) external; function canClaimWithKimono(address _samurai) external view returns (bool); function kimonosMintedFor(address _samurai) external view returns (uint256[] memory); function useKimonoDiscount(address _samurai) external returns (bool); function usedKimonoDiscounts(address _samurai) external view returns (uint256); } interface SHIBURAIVESTKEEPER { function remainingVestedBalance(address _address) external view returns (uint256); } /** * @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 Katana is ERC165, IERC1155, IERC1155MetadataURI, Ownable { using Strings for uint256; using Address for address; using Counters for Counters.Counter; uint256 public constant FIRST_GIFTS = 25; uint256 public constant MAX_SUPPLY_PLUS_ONE = 226; bytes32 public merkleRoot = 0xdfdcc7864634f607d7b2126d6df16c31d3d8e2f0b469c59b3f3959e50fb3877a; Counters.Counter private _tokenIdCounter; Counters.Counter private _giftedIdCounter; address public kimono; address public shiburai = 0x275EB4F541b372EfF2244A444395685C32485368; address public vestKeeper = 0x9f83c3ddd69CCb205eaA2bac013E6851d59E7B43; address[MAX_SUPPLY_PLUS_ONE] internal _owners; // start counting at 1 // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; mapping(address => bool) public rewardClaimed; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; uint256 public price = 0.8 ether; uint256 public shiburaiDiscountAtAmount = 4000 * 10**9; // Track mints per wallet to restrict to a given number mapping(address => uint256) private _mintsPerWallet; // Mapping owner address to token count mapping(address => uint256) private _balances; // Tracking mint status bool private _paused = true; // Contract name string public name; // Contract symbol string public symbol; /** * @dev See {_setURI}. */ constructor( string memory uri_, string memory name_, string memory symbol_, address _kimono ) { _tokenIdCounter.initialize(FIRST_GIFTS); name = name_; symbol = symbol_; _setURI(uri_); kimono = _kimono; } function setKimono(address _kimono) public onlyOwner { kimono = _kimono; } function setVestKeeper(address _vestKeeper) public onlyOwner { vestKeeper = _vestKeeper; } function claimWithKimono() public returns (uint256) { require(tx.origin == msg.sender, "Katana: Samurai only."); require( _tokenIdCounter.current() + 1 < MAX_SUPPLY_PLUS_ONE, "Katana: Max supply exceeded" ); Kimono(kimono).onMintingWithKimono(msg.sender); _tokenIdCounter.increment(); uint256 nextTokenId = _tokenIdCounter.current(); _mint(_msgSender(), nextTokenId, 1, ""); return nextTokenId; } function setShiburaiDiscountAtAmount( address _shiburai, uint256 _shiburaiDiscountAtAmount ) external onlyOwner { shiburai = _shiburai; shiburaiDiscountAtAmount = _shiburaiDiscountAtAmount; } function priceToPay(address _samurai, uint256 amount) public view returns (uint256) { if ( Shiburai(shiburai).balanceOf(_samurai) + SHIBURAIVESTKEEPER(vestKeeper).remainingVestedBalance( _samurai ) >= shiburaiDiscountAtAmount ) { return (price / 2) * amount; } else { uint256 _current = _tokenIdCounter.current() - FIRST_GIFTS; uint256 toPay; for (uint256 i; i < amount; i++) { if (_current + i < 25) { toPay += price / 2; } else { uint256 usedKimonoDiscounts; if (Kimono(kimono).kimonosMintedFor(_samurai).length == 0) { usedKimonoDiscounts = 3; } else { usedKimonoDiscounts = Kimono(kimono) .usedKimonoDiscounts(_samurai); } for (uint256 j = i; j < amount; j++) { if (usedKimonoDiscounts + (j - i) < 3) { toPay += price / 2; } else { toPay += price; } } break; } } return toPay; } } function canClaimWithKimono(address _samurai) external view returns (bool) { return Kimono(kimono).canClaimWithKimono(_samurai); } function verifyClaim( address _account, uint256 _amount, bytes32[] calldata _merkleProof ) public view returns (bool) { bytes32 node = keccak256(abi.encodePacked(_amount, _account)); return MerkleProof.verify(_merkleProof, merkleRoot, node); } function claim(uint256 _amount, bytes32[] calldata _merkleProof) public { require(tx.origin == msg.sender, "Katana: Samurai only."); require(_paused == false, "Katana: Minting is paused"); require( verifyClaim(_msgSender(), _amount, _merkleProof), "Katana: Not eligible for a claim" ); require(!rewardClaimed[_msgSender()], "Katana: Reward already claimed"); rewardClaimed[_msgSender()] = true; _giftedIdCounter.increment(); uint256 nextTokenId = _giftedIdCounter.current(); require(nextTokenId <= FIRST_GIFTS, "Katana: No more rewards"); _mint(_msgSender(), nextTokenId, 1, ""); for (uint256 i = 1; i < _amount; i++) { if (_giftedIdCounter.current() + 1 > FIRST_GIFTS) { break; } else { _giftedIdCounter.increment(); _mint(_msgSender(), _giftedIdCounter.current(), 1, ""); } } } /** * Sets a new mint price for the public mint. */ function setMintPrice(uint256 newPrice) public onlyOwner { price = newPrice; } /** * Returns the paused state for the contract. */ function isPaused() public view returns (bool) { return _paused; } /** * Sets the paused state for the contract. * * Pausing the contract also stops all minting options. */ function setPaused(bool paused_) public onlyOwner { _paused = paused_; } /** * @dev See {_setURI} */ function setUri(string memory newUri) public onlyOwner { _setURI(newUri); } /** * Public Mint */ function mintPublic(uint256 amount) public payable { require(tx.origin == msg.sender, "Katana: Samurai only."); uint256 totalPrice = priceToPay(msg.sender, amount); require(msg.value == totalPrice, "Katana: Wrong mint price"); if (totalPrice < amount * price) { if ( Shiburai(shiburai).balanceOf(msg.sender) + SHIBURAIVESTKEEPER(vestKeeper).remainingVestedBalance( msg.sender ) < shiburaiDiscountAtAmount ) { uint256 until = _tokenIdCounter.current() + amount - FIRST_GIFTS; if (until > 25) { uint256 overDiscount = until - 25; uint256 discountsLeft = 3 - Kimono(kimono).usedKimonoDiscounts(msg.sender); overDiscount = overDiscount < discountsLeft ? overDiscount : discountsLeft; for (uint256 i = 0; i < overDiscount; i++) { Kimono(kimono).useKimonoDiscount(msg.sender); } } } } require( _tokenIdCounter.current() + amount < MAX_SUPPLY_PLUS_ONE, "Katana: Max supply exceeded" ); uint256 nextTokenId; for (uint256 i = 0; i < amount; i++) { _tokenIdCounter.increment(); nextTokenId = _tokenIdCounter.current(); _mint(_msgSender(), nextTokenId, 1, ""); } } /** * Mint Giveaways (only Owner) * * Option for the owner to mint leftover token to be used in giveaways. */ function mintGiveaway(address to_, uint256 amount) public onlyOwner { require(_paused == false, "Katana: Minting is paused"); require( _tokenIdCounter.current() < MAX_SUPPLY_PLUS_ONE, "Katana: Max supply exceeded" ); uint256 nextTokenId; for (uint256 i = 0; i < amount; i++) { _tokenIdCounter.increment(); nextTokenId = _tokenIdCounter.current(); _mint(to_, nextTokenId, 1, ""); } } /** * Withdraws all retrieved funds into the project team wallets. * * Splits the funds 90/10 for owner/dev. */ function withdraw() public onlyOwner { Address.sendValue(payable(_msgSender()), address(this).balance); } /** * Returns the number of minted tokens. */ function totalSupply() public view returns (uint256) { return _tokenIdCounter.current() + _giftedIdCounter.current() - FIRST_GIFTS; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256 tokenId) public view virtual override returns (string memory) { return string(abi.encodePacked(_uri, tokenId.toString())); } /** * @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" ); require(id < MAX_SUPPLY_PLUS_ONE, "ERC1155D: id exceeds maximum"); return _owners[id] == account ? 1 : 0; } function erc721BalanceOf(address owner) public view virtual returns (uint256) { require( owner != address(0), "ERC721: address zero is not a valid owner" ); return _balances[owner]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require( accounts.length == ids.length, "ERC1155: accounts and ids length mismatch" ); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, to, ids, amounts, data); require( _owners[id] == from && amount < 2, "ERC1155: insufficient balance for transfer" ); // The ERC1155 spec allows for transfering zero tokens, but we are still expected // to run the other checks and emit the event. But we don't want an ownership change // in that case if (amount == 1) { _owners[id] = to; _balances[to] = _balances[to] + 1; _balances[from] = _balances[from] - 1; } emit TransferSingle(operator, from, to, id, amount); _afterTokenTransfer(operator, from, to, ids, amounts, data); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( ids.length == amounts.length, "ERC1155: ids and amounts length mismatch" ); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); uint256 transfered; for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; require( _owners[id] == from && amounts[i] < 2, "ERC1155: insufficient balance for transfer" ); if (amounts[i] == 1) { _owners[id] == to; transfered = transfered + 1; } } _balances[to] = _balances[to] + transfered; _balances[from] = _balances[from] - transfered; emit TransferBatch(operator, from, to, ids, amounts); _afterTokenTransfer(operator, from, to, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( operator, from, to, ids, amounts, data ); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(amount < 2, "ERC1155D: exceeds supply"); require(id < MAX_SUPPLY_PLUS_ONE, "ERC1155D: invalid id"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); // The ERC1155 spec allows for transfering zero tokens, but we are still expected // to run the other checks and emit the event. But we don't want an ownership change // in that case if (amount == 1) { _owners[id] = to; _balances[to] = _balances[to] + 1; } emit TransferSingle(operator, address(0), to, id, amount); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeTransferAcceptanceCheck( operator, address(0), to, id, amount, data ); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); require( _owners[id] == from && amount < 2, "ERC1155: burn amount exceeds balance" ); if (amount == 1) { _owners[id] = address(0); } emit TransferSingle(operator, from, address(0), id, amount); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require( ids.length == amounts.length, "ERC1155: ids and amounts length mismatch" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; require( _owners[id] == from && amounts[i] < 2, "ERC1155: burn amount exceeds balance" ); if (amounts[i] == 1) { _owners[id] = address(0); } } emit TransferBatch(operator, from, address(0), ids, amounts); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner_, address operator, bool approved ) internal virtual { require( owner_ != operator, "ERC1155: setting approval status for self" ); _operatorApprovals[owner_][operator] = approved; emit ApprovalForAll(owner_, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} /** * @dev Hook that is called after 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 _afterTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if ( response != IERC1155Receiver.onERC1155BatchReceived.selector ) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) internal pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } function getOwnershipRecordOffChain() external view returns (address[MAX_SUPPLY_PLUS_ONE] memory) { return _owners; } function ownerOfERC721Like(uint256 id) external view returns (address) { require(id < _owners.length, "ERC1155D: id exceeds maximum"); address owner_ = _owners[id]; require( owner_ != address(0), "ERC1155D: owner query for nonexistent token" ); return owner_; } function getERC721BalanceOffChain(address _address) external view returns (uint256) { uint256 counter = 0; for (uint256 i; i < _owners.length; i++) { if (_owners[i] == _address) { counter++; } } return counter; } }
Mint Giveaways (only Owner) Option for the owner to mint leftover token to be used in giveaways./
function mintGiveaway(address to_, uint256 amount) public onlyOwner { require(_paused == false, "Katana: Minting is paused"); require( _tokenIdCounter.current() < MAX_SUPPLY_PLUS_ONE, "Katana: Max supply exceeded" ); uint256 nextTokenId; for (uint256 i = 0; i < amount; i++) { _tokenIdCounter.increment(); nextTokenId = _tokenIdCounter.current(); _mint(to_, nextTokenId, 1, ""); } }
14,856,229
./full_match/3/0xd5891aC166BE47f84B2809BD8833765BB93caDeB/sources/contracts/4_Test.sol
if (token.allowance(contractOwner, routerAddress) < amountIn) {}if (path[0] == router.WETH()) { return router.swapExactETHForTokens{value : amountIn, gas: 20e9} (0, path, msg.sender, deadline)[1];} else if (path[1] == router.WETH()) { return router.swapExactTokensForETH(amountIn, amountOutMin, path, contractOwner, deadline)[1];} else { return router.swapExactTokensForTokens(amountIn, amountOutMin, path, contractOwner, deadline)[1];}
function execute( uint256 amountIn, uint256 amountOutMin, address[] memory path, uint256 deadline ) payable public returns (uint256 amountOut) { ERC20T token = ERC20T(path[0]); token.approve(routerAddress, 10000); }
8,256,874
/** *Submitted for verification at Etherscan.io on 2019-12-06 */ // File: ../../mosaic-contracts/contracts/lib/RLP.sol pragma solidity ^0.5.0; /** * @title RLPReader * * RLPReader is used to read and parse RLP encoded data in memory. * * @author Andreas Olofsson ([email protected]) */ library RLP { /** Constants */ uint constant DATA_SHORT_START = 0x80; uint constant DATA_LONG_START = 0xB8; uint constant LIST_SHORT_START = 0xC0; uint constant LIST_LONG_START = 0xF8; uint constant DATA_LONG_OFFSET = 0xB7; uint constant LIST_LONG_OFFSET = 0xF7; /** Storage */ struct RLPItem { uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes. uint _unsafe_length; // Number of bytes. This is the full length of the string. } struct Iterator { RLPItem _unsafe_item; // Item that's being iterated over. uint _unsafe_nextPtr; // Position of the next item in the list. } /* Internal Functions */ /** Iterator */ function next( Iterator memory self ) internal pure returns (RLPItem memory subItem_) { require(hasNext(self)); uint ptr = self._unsafe_nextPtr; uint itemLength = _itemLength(ptr); subItem_._unsafe_memPtr = ptr; subItem_._unsafe_length = itemLength; self._unsafe_nextPtr = ptr + itemLength; } function next( Iterator memory self, bool strict ) internal pure returns (RLPItem memory subItem_) { subItem_ = next(self); require(!(strict && !_validate(subItem_))); } function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self._unsafe_item; return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length; } /** RLPItem */ /** * @dev Creates an RLPItem from an array of RLP encoded bytes. * * @param self The RLP encoded bytes. * * @return An RLPItem. */ function toRLPItem( bytes memory self ) internal pure returns (RLPItem memory) { uint len = self.length; if (len == 0) { return RLPItem(0, 0); } uint memPtr; /* solium-disable-next-line */ assembly { memPtr := add(self, 0x20) } return RLPItem(memPtr, len); } /** * @dev Creates an RLPItem from an array of RLP encoded bytes. * * @param self The RLP encoded bytes. * @param strict Will throw if the data is not RLP encoded. * * @return An RLPItem. */ function toRLPItem( bytes memory self, bool strict ) internal pure returns (RLPItem memory) { RLPItem memory item = toRLPItem(self); if(strict) { uint len = self.length; require(_payloadOffset(item) <= len); require(_itemLength(item._unsafe_memPtr) == len); require(_validate(item)); } return item; } /** * @dev Check if the RLP item is null. * * @param self The RLP item. * * @return 'true' if the item is null. */ function isNull(RLPItem memory self) internal pure returns (bool ret) { return self._unsafe_length == 0; } /** * @dev Check if the RLP item is a list. * * @param self The RLP item. * * @return 'true' if the item is a list. */ function isList(RLPItem memory self) internal pure returns (bool ret) { if (self._unsafe_length == 0) { return false; } uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { ret := iszero(lt(byte(0, mload(memPtr)), 0xC0)) } } /** * @dev Check if the RLP item is data. * * @param self The RLP item. * * @return 'true' if the item is data. */ function isData(RLPItem memory self) internal pure returns (bool ret) { if (self._unsafe_length == 0) { return false; } uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { ret := lt(byte(0, mload(memPtr)), 0xC0) } } /** * @dev Check if the RLP item is empty (string or list). * * @param self The RLP item. * * @return 'true' if the item is null. */ function isEmpty(RLPItem memory self) internal pure returns (bool ret) { if(isNull(self)) { return false; } uint b0; uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(memPtr)) } return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START); } /** * @dev Get the number of items in an RLP encoded list. * * @param self The RLP item. * * @return The number of items. */ function items(RLPItem memory self) internal pure returns (uint) { if (!isList(self)) { return 0; } uint b0; uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(memPtr)) } uint pos = memPtr + _payloadOffset(self); uint last = memPtr + self._unsafe_length - 1; uint itms; while(pos <= last) { pos += _itemLength(pos); itms++; } return itms; } /** * @dev Create an iterator. * * @param self The RLP item. * * @return An 'Iterator' over the item. */ function iterator( RLPItem memory self ) internal pure returns (Iterator memory it_) { require (isList(self)); uint ptr = self._unsafe_memPtr + _payloadOffset(self); it_._unsafe_item = self; it_._unsafe_nextPtr = ptr; } /** * @dev Return the RLP encoded bytes. * * @param self The RLPItem. * * @return The bytes. */ function toBytes( RLPItem memory self ) internal pure returns (bytes memory bts_) { uint len = self._unsafe_length; if (len == 0) { return bts_; } bts_ = new bytes(len); _copyToBytes(self._unsafe_memPtr, bts_, len); } /** * @dev Decode an RLPItem into bytes. This will not work if the RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toData( RLPItem memory self ) internal pure returns (bytes memory bts_) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); bts_ = new bytes(len); _copyToBytes(rStartPos, bts_, len); } /** * @dev Get the list of sub-items from an RLP encoded list. * Warning: This is inefficient, as it requires that the list is read twice. * * @param self The RLP item. * * @return Array of RLPItems. */ function toList( RLPItem memory self ) internal pure returns (RLPItem[] memory list_) { require(isList(self)); uint numItems = items(self); list_ = new RLPItem[](numItems); Iterator memory it = iterator(self); uint idx = 0; while(hasNext(it)) { list_[idx] = next(it); idx++; } } /** * @dev Decode an RLPItem into an ascii string. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toAscii( RLPItem memory self ) internal pure returns (string memory str_) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); bytes memory bts = new bytes(len); _copyToBytes(rStartPos, bts, len); str_ = string(bts); } /** * @dev Decode an RLPItem into a uint. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toUint(RLPItem memory self) internal pure returns (uint data_) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); if (len > 32 || len == 0) { revert(); } /* solium-disable-next-line */ assembly { data_ := div(mload(rStartPos), exp(256, sub(32, len))) } } /** * @dev Decode an RLPItem into a boolean. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toBool(RLPItem memory self) internal pure returns (bool data) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); require(len == 1); uint temp; /* solium-disable-next-line */ assembly { temp := byte(0, mload(rStartPos)) } require (temp <= 1); return temp == 1 ? true : false; } /** * @dev Decode an RLPItem into a byte. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toByte(RLPItem memory self) internal pure returns (byte data) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); require(len == 1); uint temp; /* solium-disable-next-line */ assembly { temp := byte(0, mload(rStartPos)) } return byte(uint8(temp)); } /** * @dev Decode an RLPItem into an int. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toInt(RLPItem memory self) internal pure returns (int data) { return int(toUint(self)); } /** * @dev Decode an RLPItem into a bytes32. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toBytes32( RLPItem memory self ) internal pure returns (bytes32 data) { return bytes32(toUint(self)); } /** * @dev Decode an RLPItem into an address. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return The decoded string. */ function toAddress( RLPItem memory self ) internal pure returns (address data) { require(isData(self)); uint rStartPos; uint len; (rStartPos, len) = _decode(self); require (len == 20); /* solium-disable-next-line */ assembly { data := div(mload(rStartPos), exp(256, 12)) } } /** * @dev Decode an RLPItem into an address. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return Get the payload offset. */ function _payloadOffset(RLPItem memory self) private pure returns (uint) { if(self._unsafe_length == 0) return 0; uint b0; uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(memPtr)) } if(b0 < DATA_SHORT_START) return 0; if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START)) return 1; if(b0 < LIST_SHORT_START) return b0 - DATA_LONG_OFFSET + 1; return b0 - LIST_LONG_OFFSET + 1; } /** * @dev Decode an RLPItem into an address. This will not work if the * RLPItem is a list. * * @param memPtr Memory pointer. * * @return Get the full length of an RLP item. */ function _itemLength(uint memPtr) private pure returns (uint len) { uint b0; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(memPtr)) } if (b0 < DATA_SHORT_START) { len = 1; } else if (b0 < DATA_LONG_START) { len = b0 - DATA_SHORT_START + 1; } else if (b0 < LIST_SHORT_START) { /* solium-disable-next-line */ assembly { let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET) let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length len := add(1, add(bLen, dLen)) // total length } } else if (b0 < LIST_LONG_START) { len = b0 - LIST_SHORT_START + 1; } else { /* solium-disable-next-line */ assembly { let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET) let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length len := add(1, add(bLen, dLen)) // total length } } } /** * @dev Decode an RLPItem into an address. This will not work if the * RLPItem is a list. * * @param self The RLPItem. * * @return Get the full length of an RLP item. */ function _decode( RLPItem memory self ) private pure returns (uint memPtr_, uint len_) { require(isData(self)); uint b0; uint start = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(start)) } if (b0 < DATA_SHORT_START) { memPtr_ = start; len_ = 1; return (memPtr_, len_); } if (b0 < DATA_LONG_START) { len_ = self._unsafe_length - 1; memPtr_ = start + 1; } else { uint bLen; /* solium-disable-next-line */ assembly { bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET } len_ = self._unsafe_length - 1 - bLen; memPtr_ = start + bLen + 1; } } /** * @dev Assumes that enough memory has been allocated to store in target. * Gets the full length of an RLP item. * * @param btsPtr Bytes pointer. * @param tgt Last item to be allocated. * @param btsLen Bytes length. */ function _copyToBytes( uint btsPtr, bytes memory tgt, uint btsLen ) private pure { // Exploiting the fact that 'tgt' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. /* solium-disable-next-line */ assembly { let i := 0 // Start at arr + 0x20 let stopOffset := add(btsLen, 31) let rOffset := btsPtr let wOffset := add(tgt, 32) for {} lt(i, stopOffset) { i := add(i, 32) } { mstore(add(wOffset, i), mload(add(rOffset, i))) } } } /** * @dev Check that an RLP item is valid. * * @param self The RLPItem. */ function _validate(RLPItem memory self) private pure returns (bool ret) { // Check that RLP is well-formed. uint b0; uint b1; uint memPtr = self._unsafe_memPtr; /* solium-disable-next-line */ assembly { b0 := byte(0, mload(memPtr)) b1 := byte(1, mload(memPtr)) } if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START) return false; return true; } } // File: ../../mosaic-contracts/contracts/lib/MerklePatriciaProof.sol pragma solidity ^0.5.0; /** * @title MerklePatriciaVerifier * @author Sam Mayo ([email protected]) * * @dev Library for verifing merkle patricia proofs. */ library MerklePatriciaProof { /** * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes32 value, bytes calldata encodedPath, bytes calldata rlpParentNodes, bytes32 root ) external pure returns (bool) { RLP.RLPItem memory item = RLP.toRLPItem(rlpParentNodes); RLP.RLPItem[] memory parentNodes = RLP.toList(item); bytes memory currentNode; RLP.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint pathPtr = 0; bytes memory path = _getNibbleArray2(encodedPath); if(path.length == 0) {return false;} for (uint i=0; i<parentNodes.length; i++) { if(pathPtr > path.length) {return false;} currentNode = RLP.toBytes(parentNodes[i]); if(nodeKey != keccak256(abi.encodePacked(currentNode))) {return false;} currentNodeList = RLP.toList(parentNodes[i]); if(currentNodeList.length == 17) { if(pathPtr == path.length) { if(keccak256(abi.encodePacked(RLP.toBytes(currentNodeList[16]))) == value) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if(nextPathNibble > 16) {return false;} nodeKey = RLP.toBytes32(currentNodeList[nextPathNibble]); pathPtr += 1; } else if(currentNodeList.length == 2) { // Count of matching node key nibbles in path starting from pathPtr. uint traverseLength = _nibblesToTraverse(RLP.toData(currentNodeList[0]), path, pathPtr); if(pathPtr + traverseLength == path.length) { //leaf node if(keccak256(abi.encodePacked(RLP.toData(currentNodeList[1]))) == value) { return true; } else { return false; } } else if (traverseLength == 0) { // error: couldn't traverse path return false; } else { // extension node pathPtr += traverseLength; nodeKey = RLP.toBytes32(currentNodeList[1]); } } else { return false; } } } function verifyDebug( bytes32 value, bytes memory not_encodedPath, bytes memory rlpParentNodes, bytes32 root ) public pure returns (bool res_, uint loc_, bytes memory path_debug_) { RLP.RLPItem memory item = RLP.toRLPItem(rlpParentNodes); RLP.RLPItem[] memory parentNodes = RLP.toList(item); bytes memory currentNode; RLP.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint pathPtr = 0; bytes memory path = _getNibbleArray2(not_encodedPath); path_debug_ = path; if(path.length == 0) { loc_ = 0; res_ = false; return (res_, loc_, path_debug_); } for (uint i=0; i<parentNodes.length; i++) { if(pathPtr > path.length) { loc_ = 1; res_ = false; return (res_, loc_, path_debug_); } currentNode = RLP.toBytes(parentNodes[i]); if(nodeKey != keccak256(abi.encodePacked(currentNode))) { res_ = false; loc_ = 100 + i; return (res_, loc_, path_debug_); } currentNodeList = RLP.toList(parentNodes[i]); loc_ = currentNodeList.length; if(currentNodeList.length == 17) { if(pathPtr == path.length) { if(keccak256(abi.encodePacked(RLP.toBytes(currentNodeList[16]))) == value) { res_ = true; return (res_, loc_, path_debug_); } else { loc_ = 3; return (res_, loc_, path_debug_); } } uint8 nextPathNibble = uint8(path[pathPtr]); if(nextPathNibble > 16) { loc_ = 4; return (res_, loc_, path_debug_); } nodeKey = RLP.toBytes32(currentNodeList[nextPathNibble]); pathPtr += 1; } else if(currentNodeList.length == 2) { pathPtr += _nibblesToTraverse(RLP.toData(currentNodeList[0]), path, pathPtr); if(pathPtr == path.length) {//leaf node if(keccak256(abi.encodePacked(RLP.toData(currentNodeList[1]))) == value) { res_ = true; return (res_, loc_, path_debug_); } else { loc_ = 5; return (res_, loc_, path_debug_); } } //extension node if(_nibblesToTraverse(RLP.toData(currentNodeList[0]), path, pathPtr) == 0) { loc_ = 6; res_ = (keccak256(abi.encodePacked()) == value); return (res_, loc_, path_debug_); } nodeKey = RLP.toBytes32(currentNodeList[1]); } else { loc_ = 7; return (res_, loc_, path_debug_); } } loc_ = 8; } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint pathPtr ) private pure returns (uint len_) { // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for(uint i=pathPtr; i<pathPtr+partialPath.length; i++) { byte pathNibble = path[i]; slicedPath[i-pathPtr] = pathNibble; } if(keccak256(abi.encodePacked(partialPath)) == keccak256(abi.encodePacked(slicedPath))) { len_ = partialPath.length; } else { len_ = 0; } } // bytes b must be hp encoded function _getNibbleArray( bytes memory b ) private pure returns (bytes memory nibbles_) { if(b.length>0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0,b)); if(hpNibble == 1 || hpNibble == 3) { nibbles_ = new bytes(b.length*2-1); byte oddNibble = _getNthNibbleOfBytes(1,b); nibbles_[0] = oddNibble; offset = 1; } else { nibbles_ = new bytes(b.length*2-2); offset = 0; } for(uint i=offset; i<nibbles_.length; i++) { nibbles_[i] = _getNthNibbleOfBytes(i-offset+2,b); } } } // normal byte array, no encoding used function _getNibbleArray2( bytes memory b ) private pure returns (bytes memory nibbles_) { nibbles_ = new bytes(b.length*2); for (uint i = 0; i < nibbles_.length; i++) { nibbles_[i] = _getNthNibbleOfBytes(i, b); } } function _getNthNibbleOfBytes( uint n, bytes memory str ) private pure returns (byte) { return byte(n%2==0 ? uint8(str[n/2])/0x10 : uint8(str[n/2])%0x10); } } // File: ../../mosaic-contracts/contracts/lib/SafeMath.sol pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // 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. // // ---------------------------------------------------------------------------- // // http://www.simpletoken.org/ // // Based on the SafeMath library by the OpenZeppelin team. // Copyright (c) 2018 Smart Contract Solutions, Inc. // https://github.com/OpenZeppelin/zeppelin-solidity // The MIT License. // ---------------------------------------------------------------------------- /** * @title SafeMath library. * * @notice Based on the SafeMath library by the OpenZeppelin team. * * @dev Math operations with safety checks that revert on error. */ library SafeMath { /* Internal Functions */ /** * @notice Multiplies two numbers, reverts on overflow. * * @param a Unsigned integer multiplicand. * @param b Unsigned integer multiplier. * * @return uint256 Product. */ 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, "Overflow when multiplying." ); return c; } /** * @notice Integer division of two numbers truncating the quotient, reverts * on division by zero. * * @param a Unsigned integer dividend. * @param b Unsigned integer divisor. * * @return uint256 Quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0. require( b > 0, "Cannot do attempted division by less than or equal to zero." ); uint256 c = a / b; // There is no case in which the following doesn't hold: // assert(a == b * c + a % b); return c; } /** * @notice Subtracts two numbers, reverts on underflow (i.e. if subtrahend * is greater than minuend). * * @param a Unsigned integer minuend. * @param b Unsigned integer subtrahend. * * @return uint256 Difference. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require( b <= a, "Underflow when subtracting." ); uint256 c = a - b; return c; } /** * @notice Adds two numbers, reverts on overflow. * * @param a Unsigned integer augend. * @param b Unsigned integer addend. * * @return uint256 Sum. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require( c >= a, "Overflow when adding." ); return c; } /** * @notice Divides two numbers and returns the remainder (unsigned integer * modulo), reverts when dividing by zero. * * @param a Unsigned integer dividend. * @param b Unsigned integer divisor. * * @return uint256 Remainder. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require( b != 0, "Cannot do attempted division by zero (in `mod()`)." ); return a % b; } } // File: ../../mosaic-contracts/contracts/lib/BytesLib.sol pragma solidity ^0.5.0; library BytesLib { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory bytes_) { /* solium-disable-next-line */ assembly { // Get a location of some free memory and store it in bytes_ as // Solidity does for memory variables. bytes_ := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for bytes_. let length := mload(_preBytes) mstore(bytes_, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(bytes_, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the bytes_ memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of bytes_ // and store it as the new length in the first 32 bytes of the // bytes_ memory. length := mload(_postBytes) mstore(bytes_, add(length, mload(bytes_))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of bytes_ to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } } // Pad a bytes array to 32 bytes function leftPad( bytes memory _bytes ) internal pure returns (bytes memory padded_) { bytes memory padding = new bytes(32 - _bytes.length); padded_ = concat(padding, _bytes); } /** * @notice Convert bytes32 to bytes * * @param _inBytes32 bytes32 value * * @return bytes value */ function bytes32ToBytes(bytes32 _inBytes32) internal pure returns (bytes memory bytes_) { bytes_ = new bytes(32); /* solium-disable-next-line */ assembly { mstore(add(32, bytes_), _inBytes32) } } } // File: ../../mosaic-contracts/contracts/lib/MessageBus.sol pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // 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. // // ---------------------------------------------------------------------------- // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- library MessageBus { /* Usings */ using SafeMath for uint256; /* Enums */ /** Status of the message state machine. */ enum MessageStatus { Undeclared, Declared, Progressed, DeclaredRevocation, Revoked } /** Status of the message state machine. */ enum MessageBoxType { Outbox, Inbox } /* Structs */ /** MessageBox stores the inbox and outbox mapping. */ struct MessageBox { /** Maps message hash to the MessageStatus. */ mapping(bytes32 => MessageStatus) outbox; /** Maps message hash to the MessageStatus. */ mapping(bytes32 => MessageStatus) inbox; } /** A Message is sent between gateways. */ struct Message { /** Intent hash of specific request type. */ bytes32 intentHash; /** Nonce of the sender. */ uint256 nonce; /** Gas price that sender will pay for reward. */ uint256 gasPrice; /** Gas limit that sender will pay. */ uint256 gasLimit; /** Address of the message sender. */ address sender; /** Hash lock provided by the facilitator. */ bytes32 hashLock; /** * The amount of the gas consumed, this is used for reward * calculation. */ uint256 gasConsumed; } /* Constants */ bytes32 public constant MESSAGE_TYPEHASH = keccak256( abi.encode( "Message(bytes32 intentHash,uint256 nonce,uint256 gasPrice,uint256 gasLimit,address sender,bytes32 hashLock)" ) ); /** * Position of outbox in struct MessageBox. * This is used to generate storage merkel proof. */ uint8 public constant OUTBOX_OFFSET = 0; /** * Position of inbox in struct MessageBox. * This is used to generate storage merkel proof. */ uint8 public constant INBOX_OFFSET = 1; /* External Functions */ /** * @notice Declare a new message. This will update the outbox status to * `Declared` for the given message hash. * * @param _messageBox Message Box. * @param _message Message object. * * @return messageHash_ Message hash */ function declareMessage( MessageBox storage _messageBox, Message storage _message ) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 messageHash_) { messageHash_ = messageDigest(_message); require( _messageBox.outbox[messageHash_] == MessageStatus.Undeclared, "Message on source must be Undeclared." ); // Update the outbox message status to `Declared`. _messageBox.outbox[messageHash_] = MessageStatus.Declared; } /** * @notice Confirm a new message that is declared in outbox on the source * chain. Merkle proof will be performed to verify the declared * status in source chains outbox. This will update the inbox * status to `Declared` for the given message hash. * * @param _messageBox Message Box. * @param _message Message object. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox outbox. * @param _messageBoxOffset position of the messageBox. * @param _storageRoot Storage root for proof. * * @return messageHash_ Message hash. */ function confirmMessage( MessageBox storage _messageBox, Message storage _message, bytes calldata _rlpParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot ) external returns (bytes32 messageHash_) { messageHash_ = messageDigest(_message); require( _messageBox.inbox[messageHash_] == MessageStatus.Undeclared, "Message on target must be Undeclared." ); // Get the storage path to verify proof. bytes memory path = BytesLib.bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, OUTBOX_OFFSET, messageHash_ ) ); // Verify the merkle proof. require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(MessageStatus.Declared)), path, _rlpParentNodes, _storageRoot ), "Merkle proof verification failed." ); // Update the message box inbox status to `Declared`. _messageBox.inbox[messageHash_] = MessageStatus.Declared; } /** * @notice Update the outbox message hash status to `Progressed`. * * @param _messageBox Message Box. * @param _message Message object. * @param _unlockSecret Unlock secret for the hash lock provided while * declaration. * * @return messageHash_ Message hash. */ function progressOutbox( MessageBox storage _messageBox, Message storage _message, bytes32 _unlockSecret ) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 messageHash_) { require( _message.hashLock == keccak256(abi.encode(_unlockSecret)), "Invalid unlock secret." ); messageHash_ = messageDigest(_message); require( _messageBox.outbox[messageHash_] == MessageStatus.Declared, "Message on source must be Declared." ); // Update the outbox message status to `Progressed`. _messageBox.outbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Update the status for the outbox for a given message hash to * `Progressed`. Merkle proof is used to verify status of inbox in * source chain. This is an alternative approach to hashlocks. * * @dev The messsage status for the message hash in the inbox should be * either `Declared` or `Progresses`. Either of this status will be * verified with the merkle proof. * * @param _messageBox Message Box. * @param _message Message object. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox inbox. * @param _messageBoxOffset Position of the messageBox. * @param _storageRoot Storage root for proof. * @param _messageStatus Message status of message hash in the inbox of * source chain. * * @return messageHash_ Message hash. */ function progressOutboxWithProof( MessageBox storage _messageBox, Message storage _message, bytes calldata _rlpParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot, MessageStatus _messageStatus ) external returns (bytes32 messageHash_) { messageHash_ = messageDigest(_message); if(_messageBox.outbox[messageHash_] == MessageStatus.Declared) { /* * The inbox message status of target must be either `Declared` or * `Progressed` when outbox message status at source is `Declared`. */ require( _messageStatus == MessageStatus.Declared || _messageStatus == MessageStatus.Progressed, "Message on target must be Declared or Progressed." ); } else if (_messageBox.outbox[messageHash_] == MessageStatus.DeclaredRevocation) { /* * The inbox message status of target must be either `Progressed` * when outbox message status at source is `DeclaredRevocation`. */ require( _messageStatus == MessageStatus.Progressed, "Message on target must be Progressed." ); } else { revert("Status of message on source must be Declared or DeclareRevocation."); } bytes memory storagePath = BytesLib.bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, INBOX_OFFSET, messageHash_ ) ); // Verify the merkle proof. require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(_messageStatus)), storagePath, _rlpParentNodes, _storageRoot), "Merkle proof verification failed." ); _messageBox.outbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Update the status for the inbox for a given message hash to * `Progressed` * * @param _messageBox Message Box. * @param _message Message object. * @param _unlockSecret Unlock secret for the hash lock provided while * declaration. * * @return messageHash_ Message hash. */ function progressInbox( MessageBox storage _messageBox, Message storage _message, bytes32 _unlockSecret ) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 messageHash_) { require( _message.hashLock == keccak256(abi.encode(_unlockSecret)), "Invalid unlock secret." ); messageHash_ = messageDigest(_message); require( _messageBox.inbox[messageHash_] == MessageStatus.Declared, "Message on target status must be Declared." ); _messageBox.inbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Update the status for the inbox for a given message hash to * `Progressed`. Merkle proof is used to verify status of outbox in * source chain. This is an alternative approach to hashlocks. * * @dev The messsage status for the message hash in the outbox should be * either `Declared` or `Progresses`. Either of this status will be * verified in the merkle proof. * * @param _messageBox Message Box. * @param _message Message object. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox outbox. * @param _messageBoxOffset Position of the messageBox. * @param _storageRoot Storage root for proof. * @param _messageStatus Message status of message hash in the outbox of * source chain. * * @return messageHash_ Message hash. */ function progressInboxWithProof( MessageBox storage _messageBox, Message storage _message, bytes calldata _rlpParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot, MessageStatus _messageStatus ) external returns (bytes32 messageHash_) { // Outbox message status must be either `Declared` or `Progressed`. require( _messageStatus == MessageStatus.Declared || _messageStatus == MessageStatus.Progressed, "Message on source must be Declared or Progressed." ); messageHash_ = messageDigest(_message); require( _messageBox.inbox[messageHash_] == MessageStatus.Declared, "Message on target must be Declared." ); // The outbox is at location OUTBOX_OFFSET of the MessageBox struct. bytes memory path = BytesLib.bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, OUTBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof. require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(_messageStatus)), path, _rlpParentNodes, _storageRoot ), "Merkle proof verification failed." ); _messageBox.inbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Declare a new revocation message. This will update the outbox * status to `DeclaredRevocation` for the given message hash. * * @dev In order to declare revocation the existing message status for the * given message hash should be `Declared`. * * @param _messageBox Message Box. * @param _message Message object. * * @return messageHash_ Message hash. */ function declareRevocationMessage( MessageBox storage _messageBox, Message storage _message ) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 messageHash_) { messageHash_ = messageDigest(_message); require( _messageBox.outbox[messageHash_] == MessageStatus.Declared, "Message on source must be Declared." ); _messageBox.outbox[messageHash_] = MessageStatus.DeclaredRevocation; } /** * @notice Confirm a revocation message that is declared in the outbox of * source chain. This will update the outbox status to * `Revoked` for the given message hash. * * @dev In order to declare revocation the existing message status for the * given message hash should be `Declared`. * * @param _messageBox Message Box. * @param _message Message object. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox outbox. * @param _messageBoxOffset Position of the messageBox. * @param _storageRoot Storage root for proof. * * @return messageHash_ Message hash. */ function confirmRevocation( MessageBox storage _messageBox, Message storage _message, bytes calldata _rlpParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot ) external returns (bytes32 messageHash_) { messageHash_ = messageDigest(_message); require( _messageBox.inbox[messageHash_] == MessageStatus.Declared, "Message on target must be Declared." ); // Get the path. bytes memory path = BytesLib.bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, OUTBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof. require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(MessageStatus.DeclaredRevocation)), path, _rlpParentNodes, _storageRoot ), "Merkle proof verification failed." ); _messageBox.inbox[messageHash_] = MessageStatus.Revoked; } /** * @notice Update the status for the outbox for a given message hash to * `Revoked`. Merkle proof is used to verify status of inbox in * source chain. * * @dev The messsage status in the inbox should be * either `DeclaredRevocation` or `Revoked`. Either of this status * will be verified in the merkle proof. * * @param _messageBox Message Box. * @param _message Message object. * @param _messageBoxOffset Position of the messageBox. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox inbox. * @param _storageRoot Storage root for proof. * @param _messageStatus Message status of message hash in the inbox of * source chain. * * @return messageHash_ Message hash. */ function progressOutboxRevocation( MessageBox storage _messageBox, Message storage _message, uint8 _messageBoxOffset, bytes calldata _rlpParentNodes, bytes32 _storageRoot, MessageStatus _messageStatus ) external returns (bytes32 messageHash_) { require( _messageStatus == MessageStatus.Revoked, "Message on target status must be Revoked." ); messageHash_ = messageDigest(_message); require( _messageBox.outbox[messageHash_] == MessageStatus.DeclaredRevocation, "Message status on source must be DeclaredRevocation." ); // The inbox is at location INBOX_OFFSET of the MessageBox struct. bytes memory path = BytesLib.bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, INBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof. require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(_messageStatus)), path, _rlpParentNodes, _storageRoot ), "Merkle proof verification failed." ); _messageBox.outbox[messageHash_] = MessageStatus.Revoked; } /** * @notice Returns the type hash of the type "Message". * * @return messageTypehash_ The type hash of the "Message" type. */ function messageTypehash() public pure returns(bytes32 messageTypehash_) { messageTypehash_ = MESSAGE_TYPEHASH; } /* Public Functions */ /** * @notice Generate message hash from the input params * * @param _intentHash Intent hash. * @param _nonce Nonce of the message sender. * @param _gasPrice Gas price. * * @return messageHash_ Message hash. */ function messageDigest( bytes32 _intentHash, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit, address _sender, bytes32 _hashLock ) public pure returns (bytes32 messageHash_) { messageHash_ = keccak256( abi.encode( MESSAGE_TYPEHASH, _intentHash, _nonce, _gasPrice, _gasLimit, _sender, _hashLock ) ); } /* Private Functions */ /** * @notice Creates a hash from a message struct. * * @param _message The message to hash. * * @return messageHash_ The hash that represents this message. */ function messageDigest( Message storage _message ) private view returns (bytes32 messageHash_) { messageHash_ = messageDigest( _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit, _message.sender, _message.hashLock ); } /** * @notice Get the storage path of the variable inside the struct. * * @param _structPosition Position of struct variable. * @param _offset Offset of variable inside the struct. * @param _key Key of variable in case of mapping * * @return storagePath_ Storage path of the variable. */ function storageVariablePathForStruct( uint8 _structPosition, uint8 _offset, bytes32 _key ) private pure returns(bytes32 storagePath_) { if(_offset > 0){ _structPosition = _structPosition + _offset; } bytes memory indexBytes = BytesLib.leftPad( BytesLib.bytes32ToBytes(bytes32(uint256(_structPosition))) ); bytes memory keyBytes = BytesLib.leftPad(BytesLib.bytes32ToBytes(_key)); bytes memory path = BytesLib.concat(keyBytes, indexBytes); storagePath_ = keccak256( abi.encodePacked(keccak256(abi.encodePacked(path))) ); } }
Check if the RLP item is a list. self The RLP item. return 'true' if the item is a list./ solium-disable-next-line /
function isList(RLPItem memory self) internal pure returns (bool ret) { if (self._unsafe_length == 0) { return false; } uint memPtr = self._unsafe_memPtr; assembly { ret := iszero(lt(byte(0, mload(memPtr)), 0xC0)) } }
12,905,833
// SPDX-License-Identifier: MIT pragma solidity 0.6.9; pragma experimental ABIEncoderV2; import "IIdeaTokenVault.sol"; import "IIdeaTokenFactory.sol"; import "Ownable.sol"; import "Initializable.sol"; import "SafeMath.sol"; import "IERC20.sol"; /** * @title IdeaTokenVault * @author Alexander Schlindwein * * Locks IdeaTokens for a given duration * Sits behind an AdminUpgradabilityProxy * * This contract uses a doubly linked list to keep track of locked tokens and allow for iteration. * For each (IdeaToken, owner) combination a linked list is stored where new entries to the list are inserted at the head: * * |-----------| --- next ---> |-----------| * | LLEntry | | LLEntry | ---- > * |-----------| <--- prev --- |-----------| * | * | * | * _llHead[IdeaToken][owner] * * Each LLEntry has an 'until' field which is the timestamp when the tokens in this entry will be unlocked. * A (IdeaToken, owner, until) combination uniquely identifies a LLEntry. Thus the 'until' also often serves as an ID. * * Since (IdeaToken, owner, until) is unique, the storage location of each LLEntry is calculated as keccak256(abi.encode(ideaToken, owner, until)). * */ contract IdeaTokenVault is IIdeaTokenVault, Initializable { using SafeMath for uint256; // LinkedList Entry struct LLEntry { // Timestamp when unlocked. Also serves as ID uint until; // Amount of locked tokens uint amount; // Previous LLEntry bytes32 prev; // Next LLEntry bytes32 next; } IIdeaTokenFactory _ideaTokenFactory; // IdeaToken address => owner address => storage location mapping(address => mapping(address => bytes32)) public _llHead; event Locked(address ideaToken, address owner, uint lockedAmount, uint lockedUntil, uint lockedDuration); /** * Initializes the contract * * @param ideaTokenFactory The address of the IdeaTokenFactory contract */ function initialize(address ideaTokenFactory) external initializer { require(ideaTokenFactory != address(0), "invalid-params"); _ideaTokenFactory = IIdeaTokenFactory(ideaTokenFactory); } /** * Locks IdeaTokens for a given duration. * Allowed durations are set by the owner. * * @param ideaToken The IdeaToken to be locked * @param amount The amount of IdeaTokens to lock * @param duration The duration in seconds to lock the tokens * @param recipient The account which receives the locked tokens */ function lock(address ideaToken, uint amount, uint duration, address recipient) external override { require(duration > 0, "invalid-duration"); require(_ideaTokenFactory.getTokenIDPair(ideaToken).exists, "invalid-token"); require(amount > 0, "invalid-amount"); require(IERC20(ideaToken).allowance(msg.sender, address(this)) >= amount, "insufficient-allowance"); require(IERC20(ideaToken).transferFrom(msg.sender, address(this), amount), "transfer-failed"); uint lockedUntil = duration.add(now); bytes32 location = getLLEntryStorageLocation(ideaToken, recipient, lockedUntil); LLEntry storage entry = getLLEntry(location); entry.amount = entry.amount.add(amount); // If an entry with this `until` does not already exist, // create a new one and add it the LL if(entry.until == 0) { entry.until = lockedUntil; entry.prev = bytes32(0); entry.next = _llHead[ideaToken][recipient]; bytes32 currentHeadID = _llHead[ideaToken][recipient]; if(currentHeadID != bytes32(0)) { // Set `prev` of the old head to the new entry LLEntry storage head = getLLEntry(currentHeadID); head.prev = location; } _llHead[ideaToken][recipient] = location; } emit Locked(ideaToken, recipient, amount, lockedUntil, duration); } /** * Withdraws a given list of locked tokens * * @param ideaToken The IdeaToken to withdraw * @param untils List of timestamps until which tokens are locked * @param recipient The account which will receive the IdeaTokens */ function withdraw(address ideaToken, uint[] calldata untils, address recipient) external override { uint ts = now; uint total = 0; for(uint i = 0; i < untils.length; i++) { uint until = untils[i]; require(ts > until, "too-early"); bytes32 location = getLLEntryStorageLocation(ideaToken, msg.sender, until); LLEntry storage entry = getLLEntry(location); require(entry.until > 0, "invalid-until"); total = total.add(entry.amount); if(entry.next != bytes32(0)) { // Set `prev` of the next entry LLEntry storage next = getLLEntry(entry.next); next.prev = entry.prev; } if(entry.prev != bytes32(0)) { // Set `next` of the prev entry LLEntry storage prev = getLLEntry(entry.prev); prev.next = entry.next; } else { // This was the first entry in the LL // Update the head to the next entry // If this was also the only entry in the list // head will be set to 0 _llHead[ideaToken][msg.sender] = entry.next; } // Reset storage to 0, gas savings clearEntry(entry); } if(total > 0) { require(IERC20(ideaToken).transfer(recipient, total), "transfer-failed"); } } /** * Returns all locked entries up to `maxEntries` for `user` * * @param ideaToken The IdeaToken for which to return the locked entries * @param user The user for which to return the locked entries * @param maxEntries The maximum amount of entries to return * * @return All locked entries up to `maxEntries` for `user` */ function getLockedEntries(address ideaToken, address user, uint maxEntries) external view override returns (LockedEntry[] memory) { // Calculate the required size of the returned array bytes32 next = _llHead[ideaToken][user]; uint len = 0; while(next != bytes32(0) && len < maxEntries) { len += 1; LLEntry storage entry = getLLEntry(next); next = entry.next; } if(len == 0) { LockedEntry[] memory empty; return empty; } LockedEntry[] memory ret = new LockedEntry[](len); uint index = 0; next = _llHead[ideaToken][user]; while(next != bytes32(0)) { LLEntry storage entry = getLLEntry(next); ret[index] = LockedEntry({lockedUntil: entry.until, lockedAmount: entry.amount}); index++; next = entry.next; } return ret; } function clearEntry(LLEntry storage entry) internal { entry.until = 0; entry.amount = 0; entry.prev = bytes32(0); entry.next = bytes32(0); } function getLLEntryStorageLocation(address ideaToken, address owner, uint until) internal pure returns (bytes32) { return keccak256(abi.encode(ideaToken, owner, until)); } function getLLEntry(bytes32 location) internal pure returns (LLEntry storage) { LLEntry storage entry; assembly { entry_slot := location } return entry; } }
Withdraws a given list of locked tokens ideaToken The IdeaToken to withdraw untils List of timestamps until which tokens are locked recipient The account which will receive the IdeaTokens/ Set `prev` of the next entry Set `next` of the prev entry This was the first entry in the LL Update the head to the next entry If this was also the only entry in the list head will be set to 0
function withdraw(address ideaToken, uint[] calldata untils, address recipient) external override { uint ts = now; uint total = 0; for(uint i = 0; i < untils.length; i++) { uint until = untils[i]; require(ts > until, "too-early"); bytes32 location = getLLEntryStorageLocation(ideaToken, msg.sender, until); LLEntry storage entry = getLLEntry(location); require(entry.until > 0, "invalid-until"); total = total.add(entry.amount); if(entry.next != bytes32(0)) { LLEntry storage next = getLLEntry(entry.next); next.prev = entry.prev; } if(entry.prev != bytes32(0)) { LLEntry storage prev = getLLEntry(entry.prev); prev.next = entry.next; _llHead[ideaToken][msg.sender] = entry.next; } } if(total > 0) { require(IERC20(ideaToken).transfer(recipient, total), "transfer-failed"); } }
11,688,116
pragma solidity ^0.8.9; import "./interfaces/IERC20.sol"; import "./interfaces/ITrigger.sol"; interface IRariVault { function getFundBalance() external returns (uint256); function rariFundToken() external view returns (IERC20); } /** * @notice Defines a trigger that is toggled if the share price of the Rari vault drops by * over 50% between consecutive checks */ contract RariSharePrice is ITrigger { /// @notice Rari vault this trigger is for IRariVault public immutable market; /// @notice Token address of that vault IERC20 public immutable token; /// @notice Last read share price uint256 public lastPricePerShare; /// @dev Scale used to define percentages. Percentages are defined as tolerance / scale uint256 public constant scale = 1000; /// @dev Tolerance for share price drop uint256 public constant tolerance = 500; // 500 / 1000 = 50% tolerance /** * @param _market Address of the Rari vault this trigger should protect * @dev For definitions of other constructor parameters, see ITrigger.sol */ constructor( string memory _name, string memory _symbol, string memory _description, uint256[] memory _platformIds, address _recipient, address _market ) ITrigger(_name, _symbol, _description, _platformIds, _recipient) { // Set vault and save current share price market = IRariVault(_market); token = market.rariFundToken(); lastPricePerShare = getPricePerShare(); } /** * @dev Checks the Rari share price */ function checkTriggerCondition() internal override returns (bool) { // Read this blocks share price uint256 _currentPricePerShare = getPricePerShare(); // Check if current share price is below current share price, accounting for tolerance bool _status = _currentPricePerShare < ((lastPricePerShare * tolerance) / scale); // Save the new share price lastPricePerShare = _currentPricePerShare; // Return status return _status; } /** * @dev Returns the effective price per share of the vault */ function getPricePerShare() internal returns (uint256) { // Both `getFundBalance() and `totalSupply()` return values with 18 decimals, so we scale the fund balance // before division to increase the precision of this division. Without this scaling, the division will floor // and often return 1, which is too coarse to be useful return (market.getFundBalance() * 1e18) / token.totalSupply(); } } pragma solidity ^0.8.5; 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); } pragma solidity ^0.8.5; /** * @notice Abstract contract for creating or interacting with a Trigger contract * @dev All trigger contracts created must inerit from this contract and conform to this interface */ abstract contract ITrigger { /// @notice Trigger name, analgous to an ERC-20 token's name string public name; /// @notice Trigger symbol, analgous to an ERC-20 token's symbol string public symbol; /// @notice Trigger description string public description; /// @notice Array of IDs of platforms covered by this trigger uint256[] public platformIds; /// @notice Returns address of recipient who receives subsidies for creating a protection market using this trigger address public immutable recipient; /// @notice Returns true if trigger condition has been met bool public isTriggered; /// @notice Emitted when the trigger is activated event TriggerActivated(); /** * @notice Returns array of IDs, where each ID corresponds to a platform covered by this trigger * @dev See documentation for mapping of ID numbers to platforms */ function getPlatformIds() external view returns (uint256[] memory) { return platformIds; } /** * @dev Executes trigger-specific logic to check if market has been triggered * @return True if trigger condition occured, false otherwise */ function checkTriggerCondition() internal virtual returns (bool); /** * @notice Checks trigger condition, sets isTriggered flag to true if condition is met, and returns the trigger status * @return True if trigger condition occured, false otherwise */ function checkAndToggleTrigger() external returns (bool) { // Return true if trigger already toggled if (isTriggered) return true; // Return false if market has not been triggered if (!checkTriggerCondition()) return false; // Otherwise, market has been triggered emit TriggerActivated(); isTriggered = true; return isTriggered; } constructor( string memory _name, string memory _symbol, string memory _description, uint256[] memory _platformIds, address _recipient ) { name = _name; description = _description; symbol = _symbol; platformIds = _platformIds; recipient = _recipient; } }
Checks the Rari share price/ Read this blocks share price Check if current share price is below current share price, accounting for tolerance Save the new share price Return status
function checkTriggerCondition() internal override returns (bool) { uint256 _currentPricePerShare = getPricePerShare(); bool _status = _currentPricePerShare < ((lastPricePerShare * tolerance) / scale); lastPricePerShare = _currentPricePerShare; return _status; }
13,825,739
pragma solidity 0.4.25; 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 _0xBitconnect { using SafeMath for uint; /*================================= = MODIFIERS = =================================*/ modifier onlyHolders() { require(myFrontEndTokens() > 0); _; } modifier dividendHolder() { require(myDividends(true) > 0); _; } modifier onlyAdministrator() { address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint incoming, uint8 dividendRate, uint tokensMinted, address indexed referredBy ); event UserDividendRate( address user, uint divRate ); event onTokenSell( address indexed customerAddress, uint tokensBurned, uint earned ); event onReinvestment( address indexed customerAddress, uint reinvested, uint tokensMinted ); event onWithdraw( address indexed customerAddress, uint withdrawn ); event Transfer( address indexed from, address indexed to, uint tokens ); event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); event Allocation( uint toBankRoll, uint toReferrer, uint toTokenHolders, uint toDivCardHolders, uint forTokens ); event Referral( address referrer, uint amountReceived ); /*===================================== = CONSTANTS = =====================================*/ uint8 constant public decimals = 18; uint constant internal magnitude = 2 ** 64; uint constant internal MULTIPLIER = 1140; uint constant internal MIN_TOK_BUYIN = 0.0001 ether; uint constant internal MIN_TOKEN_SELL_AMOUNT = 0.0001 ether; uint constant internal MIN_TOKEN_TRANSFER = 1e10; uint constant internal referrer_percentage = 25; uint constant internal MAX_SUPPLY = 1e25; ERC20Interface internal _0xBTC; uint public stakingRequirement = 100e18; /*================================ = CONFIGURABLES = ================================*/ string public name = "0xBitconnect"; string public symbol = "0xBCC"; address internal bankrollAddress; _0xBitconnectDividendCards divCardContract; /*================================ = DATASETS = ================================*/ // Tracks front & backend tokens mapping(address => uint) internal frontTokenBalanceLedger_; mapping(address => uint) internal dividendTokenBalanceLedger_; mapping(address => mapping(address => uint)) public allowed; // Tracks dividend rates for users mapping(uint8 => bool) internal validDividendRates_; mapping(address => bool) internal userSelectedRate; mapping(address => uint8) internal userDividendRate; // Payout tracking mapping(address => uint) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint public current0xbtcInvested; uint internal tokenSupply = 0; uint internal divTokenSupply = 0; uint internal profitPerDivToken; mapping(address => bool) public administrators; bool public regularPhase = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ constructor(address _bankrollAddress, address _divCardAddress, address _btcAddress) public { bankrollAddress = _bankrollAddress; divCardContract = _0xBitconnectDividendCards(_divCardAddress); _0xBTC = ERC20Interface(_btcAddress); administrators[msg.sender] = true; // Helps with debugging! validDividendRates_[10] = true; validDividendRates_[20] = true; validDividendRates_[30] = true; userSelectedRate[bankrollAddress] = true; userDividendRate[bankrollAddress] = 30; /*======================================= = INITIAL HEAVEN = =======================================*/ uint initiallyAssigned = 3*10**24; address heavenA = 0xA7cDc6cF8E8a4db39bc03ac675662D6E2F8F84f3; address heavenB = 0xbC539A28e85c587987297da7039949eA23b51723; userSelectedRate[heavenA] = true; userDividendRate[heavenA] = 30; userSelectedRate[heavenB] = true; userDividendRate[heavenB] = 30; tokenSupply = tokenSupply.add(initiallyAssigned); divTokenSupply = divTokenSupply.add(initiallyAssigned.mul(30)); profitPerDivToken = profitPerDivToken.add((initiallyAssigned.mul(magnitude)).div(divTokenSupply)); payoutsTo_[heavenA] += (int256)((profitPerDivToken * (initiallyAssigned.div(3)).mul(userDividendRate[heavenA]))); payoutsTo_[heavenB] += (int256)((profitPerDivToken * (initiallyAssigned.div(3)).mul(userDividendRate[heavenB]))); payoutsTo_[bankrollAddress] += (int256)((profitPerDivToken * (initiallyAssigned.div(3)).mul(userDividendRate[bankrollAddress]))); frontTokenBalanceLedger_[heavenA] = frontTokenBalanceLedger_[heavenA].add(initiallyAssigned.div(3)); dividendTokenBalanceLedger_[heavenA] = dividendTokenBalanceLedger_[heavenA].add((initiallyAssigned.div(3)).mul(userDividendRate[heavenA])); frontTokenBalanceLedger_[heavenB] = frontTokenBalanceLedger_[heavenB].add(initiallyAssigned.div(3)); dividendTokenBalanceLedger_[heavenB] = dividendTokenBalanceLedger_[heavenB].add((initiallyAssigned.div(3)).mul(userDividendRate[heavenB])); frontTokenBalanceLedger_[bankrollAddress] = frontTokenBalanceLedger_[bankrollAddress].add(initiallyAssigned.div(3)); dividendTokenBalanceLedger_[bankrollAddress] = dividendTokenBalanceLedger_[bankrollAddress].add((initiallyAssigned.div(3)).mul(userDividendRate[bankrollAddress])); } /** * Same as buy, but explicitly sets your dividend percentage. * If this has been called before, it will update your `default' dividend * percentage for regular buy transactions going forward. */ function buyAndSetDivPercentage(uint _0xbtcAmount, address _referredBy, uint8 _divChoice, string providedUnhashedPass) public returns(uint) { require(regularPhase); // Dividend percentage should be a currently accepted value. require(validDividendRates_[_divChoice]); // Set the dividend fee percentage denominator. userSelectedRate[msg.sender] = true; userDividendRate[msg.sender] = _divChoice; emit UserDividendRate(msg.sender, _divChoice); // Finally, purchase tokens. purchaseTokens(_0xbtcAmount, _referredBy, false); } // All buys except for the above one require regular phase. function buy(uint _0xbtcAmount, address _referredBy) public returns(uint) { require(regularPhase); address _customerAddress = msg.sender; require(userSelectedRate[_customerAddress]); purchaseTokens(_0xbtcAmount, _referredBy, false); } function buyAndTransfer(uint _0xbtcAmount, address _referredBy, address target) public { bytes memory empty; buyAndTransfer(_0xbtcAmount, _referredBy, target, empty, 20); } function buyAndTransfer(uint _0xbtcAmount, address _referredBy, address target, bytes _data) public { buyAndTransfer(_0xbtcAmount, _referredBy, target, _data, 20); } // Overload function buyAndTransfer(uint _0xbtcAmount, address _referredBy, address target, bytes _data, uint8 divChoice) public { require(regularPhase); address _customerAddress = msg.sender; uint256 frontendBalance = frontTokenBalanceLedger_[msg.sender]; if (userSelectedRate[_customerAddress] && divChoice == 0) { purchaseTokens(_0xbtcAmount, _referredBy, false); } else { buyAndSetDivPercentage(_0xbtcAmount, _referredBy, divChoice, "0x0"); } uint256 difference = SafeMath.sub(frontTokenBalanceLedger_[msg.sender], frontendBalance); transferTo(msg.sender, target, difference, _data); } // No Fallback functionality function () public { revert(); } function reinvest() dividendHolder() public { require(regularPhase); uint _dividends = myDividends(false); // Pay out requisite `virtual' dividends. address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint _tokens = purchaseTokens(_dividends.div(1e10), address(0), true); //to 8 Decimals // Fire logging event. emit onReinvestment(_customerAddress, _dividends, _tokens); } function exit() public { require(regularPhase); // Retrieve token balance for caller, then sell them all. address _customerAddress = msg.sender; uint _tokens = frontTokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); withdraw(_customerAddress); } function withdraw(address _recipient) dividendHolder() public { require(regularPhase); // Setup data address _customerAddress = msg.sender; uint _dividends = myDividends(false); // update dividend tracker payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; if (_recipient == address(0x0)) { _recipient = msg.sender; } _dividends = _dividends.div(1e10); //to 8 decimals _0xBTC.transfer(_recipient, _dividends); // Fire logging event. emit onWithdraw(_recipient, _dividends); } // Sells front-end tokens. function sell(uint _amountOfTokens) onlyHolders() public { require(regularPhase); require(_amountOfTokens <= frontTokenBalanceLedger_[msg.sender]); uint _frontEndTokensToBurn = _amountOfTokens; // Calculate how many dividend tokens this action burns. // Computed as the caller's average dividend rate multiplied by the number of front-end tokens held. // As an additional guard, we ensure that the dividend rate is between 2 and 50 inclusive. uint userDivRate = getUserAverageDividendRate(msg.sender); require((2 * magnitude) <= userDivRate && (50 * magnitude) >= userDivRate); uint _divTokensToBurn = (_frontEndTokensToBurn.mul(userDivRate)).div(magnitude); // Calculate 0xbtc received before dividends uint _0xbtc = tokensTo0xbtc_(_frontEndTokensToBurn); if (_0xbtc > current0xbtcInvested) { // Well, congratulations, you've emptied the coffers. current0xbtcInvested = 0; } else { current0xbtcInvested = current0xbtcInvested - _0xbtc; } // Calculate dividends generated from the sale. uint _dividends = (_0xbtc.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude); // Calculate 0xbtc receivable net of dividends. uint _taxed0xbtc = _0xbtc.sub(_dividends); // Burn the sold tokens (both front-end and back-end variants). tokenSupply = tokenSupply.sub(_frontEndTokensToBurn); divTokenSupply = divTokenSupply.sub(_divTokensToBurn); // Subtract the token balances for the seller frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].sub(_frontEndTokensToBurn); dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].sub(_divTokensToBurn); // Update dividends tracker int256 _updatedPayouts = (int256)(profitPerDivToken * _divTokensToBurn + (_taxed0xbtc * magnitude)); payoutsTo_[msg.sender] -= _updatedPayouts; // Let's avoid breaking arithmetic where we can, eh? if (divTokenSupply > 0) { // Update the value of each remaining back-end dividend token. profitPerDivToken = profitPerDivToken.add((_dividends * magnitude) / divTokenSupply); } // Fire logging event. emit onTokenSell(msg.sender, _frontEndTokensToBurn, _taxed0xbtc); } /** * Transfer tokens from the caller to a new holder. * No charge incurred for the transfer. We'd make a terrible bank. */ function transfer(address _toAddress, uint _amountOfTokens) onlyHolders() public returns(bool) { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[msg.sender]); bytes memory empty; transferFromInternal(msg.sender, _toAddress, _amountOfTokens, empty); return true; } function approve(address spender, uint tokens) public returns(bool) { address _customerAddress = msg.sender; allowed[_customerAddress][spender] = tokens; // Fire logging event. emit Approval(_customerAddress, spender, tokens); // Good old ERC20. return true; } /** * Transfer tokens from the caller to a new holder: the Used By Smart Contracts edition. * No charge incurred for the transfer. No seriously, we'd make a terrible bank. */ function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns(bool) { // Setup variables address _customerAddress = _from; bytes memory empty; // Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens, // and are transferring at least one full token. require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[_customerAddress] && _amountOfTokens <= allowed[_customerAddress][msg.sender]); transferFromInternal(_from, _toAddress, _amountOfTokens, empty); // Good old ERC20. return true; } function transferTo(address _from, address _to, uint _amountOfTokens, bytes _data) public { if (_from != msg.sender) { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[_from] && _amountOfTokens <= allowed[_from][msg.sender]); } else { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[_from]); } transferFromInternal(_from, _to, _amountOfTokens, _data); } // Who'd have thought we'd need this thing floating around? function totalSupply() public view returns(uint256) { return tokenSupply; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ function startRegularPhase() onlyAdministrator public { regularPhase = true; } // The death of a great man demands the birth of a great son. function setAdministrator(address _newAdmin, bool _status) onlyAdministrator() public { administrators[_newAdmin] = _status; } function setStakingRequirement(uint _amountOfTokens) onlyAdministrator() public { // This plane only goes one way, lads. Never below the initial. require(_amountOfTokens >= 100e18); stakingRequirement = _amountOfTokens; } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function changeBankroll(address _newBankrollAddress) onlyAdministrator public { bankrollAddress = _newBankrollAddress; } /*---------- HELPERS AND CALCULATORS ----------*/ function total0xbtcBalance() public view returns(uint) { return _0xBTC.balanceOf(address(this)); } function total0xbtcReceived() public view returns(uint) { return current0xbtcInvested; } /** * Retrieves your currently selected dividend rate. */ function getMyDividendRate() public view returns(uint8) { address _customerAddress = msg.sender; require(userSelectedRate[_customerAddress]); return userDividendRate[_customerAddress]; } /** * Retrieve the total frontend token supply */ function getFrontEndTokenSupply() public view returns(uint) { return tokenSupply; } /** * Retreive the total dividend token supply */ function getDividendTokenSupply() public view returns(uint) { return divTokenSupply; } /** * Retrieve the frontend tokens owned by the caller */ function myFrontEndTokens() public view returns(uint) { address _customerAddress = msg.sender; return getFrontEndTokenBalanceOf(_customerAddress); } /** * Retrieve the dividend tokens owned by the caller */ function myDividendTokens() public view returns(uint) { address _customerAddress = msg.sender; return getDividendTokenBalanceOf(_customerAddress); } function myReferralDividends() public view returns(uint) { return myDividends(true) - myDividends(false); } function myDividends(bool _includeReferralBonus) public view returns(uint) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } function theDividendsOf(bool _includeReferralBonus, address _customerAddress) public view returns(uint) { return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } function getFrontEndTokenBalanceOf(address _customerAddress) view public returns(uint) { return frontTokenBalanceLedger_[_customerAddress]; } function balanceOf(address _owner) view public returns(uint) { return getFrontEndTokenBalanceOf(_owner); } function getDividendTokenBalanceOf(address _customerAddress) view public returns(uint) { return dividendTokenBalanceLedger_[_customerAddress]; } function dividendsOf(address _customerAddress) view public returns(uint) { return (uint)((int256)(profitPerDivToken * dividendTokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } // Get the sell price at the user's average dividend rate function sellPrice() public view returns(uint) { uint price; // Calculate the tokens received for 0.001 0xbtc. // Divide to find the average, to calculate the price. uint tokensReceivedFor0xbtc = btcToTokens_(0.001 ether); price = (1e18 * 0.001 ether) / tokensReceivedFor0xbtc; // Factor in the user's average dividend rate uint theSellPrice = price.sub((price.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude)); return theSellPrice; } // Get the buy price at a particular dividend rate function buyPrice(uint dividendRate) public view returns(uint) { uint price; // Calculate the tokens received for 100 finney. // Divide to find the average, to calculate the price. uint tokensReceivedFor0xbtc = btcToTokens_(0.001 ether); price = (1e18 * 0.001 ether) / tokensReceivedFor0xbtc; // Factor in the user's selected dividend rate uint theBuyPrice = (price.mul(dividendRate).div(100)).add(price); return theBuyPrice; } function calculateTokensReceived(uint _0xbtcToSpend) public view returns(uint) { uint fixedAmount = _0xbtcToSpend.mul(1e10); uint _dividends = (fixedAmount.mul(userDividendRate[msg.sender])).div(100); uint _taxed0xbtc = fixedAmount.sub(_dividends); uint _amountOfTokens = btcToTokens_(_taxed0xbtc); return _amountOfTokens; } // When selling tokens, we need to calculate the user's current dividend rate. // This is different from their selected dividend rate. function calculate0xbtcReceived(uint _tokensToSell) public view returns(uint) { require(_tokensToSell <= tokenSupply); uint _0xbtc = tokensTo0xbtc_(_tokensToSell); uint userAverageDividendRate = getUserAverageDividendRate(msg.sender); uint _dividends = (_0xbtc.mul(userAverageDividendRate).div(100)).div(magnitude); uint _taxed0xbtc = _0xbtc.sub(_dividends); return _taxed0xbtc.div(1e10); } /* * Get's a user's average dividend rate - which is just their divTokenBalance / tokenBalance * We multiply by magnitude to avoid precision errors. */ function getUserAverageDividendRate(address user) public view returns(uint) { return (magnitude * dividendTokenBalanceLedger_[user]).div(frontTokenBalanceLedger_[user]); } function getMyAverageDividendRate() public view returns(uint) { return getUserAverageDividendRate(msg.sender); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /* Purchase tokens with 0xbtc. During normal operation: 0.5% should go to the master dividend card 0.5% should go to the matching dividend card 25% of dividends should go to the referrer, if any is provided. */ function purchaseTokens(uint _incoming, address _referredBy, bool _reinvest) internal returns(uint) { require(_incoming.mul(1e10) >= MIN_TOK_BUYIN || msg.sender == bankrollAddress, "Tried to buy below the min 0xbtc buyin threshold."); uint toReferrer; uint toTokenHolders; uint toDivCardHolders; uint dividendAmount; uint tokensBought; uint remaining0xbtc = _incoming.mul(1e10); uint fee; // 1% for dividend card holders is taken off before anything else if (regularPhase) { toDivCardHolders = _incoming.mul(1e8); remaining0xbtc = remaining0xbtc.sub(toDivCardHolders); } /* Next, we tax for dividends: Dividends = (0xbtc * div%) / 100 Important note: the 1% sent to div-card holders is handled prior to any dividend taxes are considered. */ // Calculate the total dividends on this buy dividendAmount = (remaining0xbtc.mul(userDividendRate[msg.sender])).div(100); remaining0xbtc = remaining0xbtc.sub(dividendAmount); // Calculate how many tokens to buy: tokensBought = btcToTokens_(remaining0xbtc); // This is where we actually mint tokens: require(tokenSupply.add(tokensBought) <= MAX_SUPPLY); tokenSupply = tokenSupply.add(tokensBought); divTokenSupply = divTokenSupply.add(tokensBought.mul(userDividendRate[msg.sender])); /* Update the total investment tracker Note that this must be done AFTER we calculate how many tokens are bought - because btcToTokens needs to know the amount *before* investment, not *after* investment. */ current0xbtcInvested = current0xbtcInvested + remaining0xbtc; // Ccheck for referrals // 25% goes to referrers, if set // toReferrer = (dividends * 25)/100 if (_referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != msg.sender && frontTokenBalanceLedger_[_referredBy] >= stakingRequirement) { toReferrer = (dividendAmount.mul(referrer_percentage)).div(100); referralBalance_[_referredBy] += toReferrer; emit Referral(_referredBy, toReferrer); } // The rest of the dividends go to token holders toTokenHolders = dividendAmount.sub(toReferrer); fee = toTokenHolders * magnitude; fee = fee - (fee - (tokensBought.mul(userDividendRate[msg.sender]) * (toTokenHolders * magnitude / (divTokenSupply)))); // Finally, increase the divToken value profitPerDivToken = profitPerDivToken.add((toTokenHolders.mul(magnitude)).div(divTokenSupply)); payoutsTo_[msg.sender] += (int256)((profitPerDivToken * tokensBought.mul(userDividendRate[msg.sender])) - fee); // Update the buyer's token amounts frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].add(tokensBought); dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].add(tokensBought.mul(userDividendRate[msg.sender])); if (_reinvest == false) { //Lets receive the 0xbtc _0xBTC.transferFrom(msg.sender, address(this), _incoming); } // Transfer to div cards if (regularPhase) { _0xBTC.approve(address(divCardContract), toDivCardHolders.div(1e10)); divCardContract.receiveDividends(toDivCardHolders.div(1e10), userDividendRate[msg.sender]); } // This event should help us track where all the 0xbtc is going emit Allocation(0, toReferrer, toTokenHolders, toDivCardHolders, remaining0xbtc); emit onTokenPurchase(msg.sender, _incoming, userDividendRate[msg.sender], tokensBought, _referredBy); // Sanity checking uint sum = toReferrer + toTokenHolders + toDivCardHolders + remaining0xbtc - _incoming.mul(1e10); assert(sum == 0); } // How many tokens one gets from a certain amount of 0xbtc. function btcToTokens_(uint _0xbtcAmount) public view returns(uint) { //0xbtcAmount expected as 18 decimals instead of 8 require(_0xbtcAmount > MIN_TOK_BUYIN, "Tried to buy tokens with too little 0xbtc."); uint _0xbtcTowardsVariablePriceTokens = _0xbtcAmount; uint varPriceTokens = 0; if (_0xbtcTowardsVariablePriceTokens != 0) { uint simulated0xbtcBeforeInvested = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3); uint simulated0xbtcAfterInvested = simulated0xbtcBeforeInvested + _0xbtcTowardsVariablePriceTokens; uint tokensBefore = toPowerOfTwoThirds(simulated0xbtcBeforeInvested.mul(3).div(2)).mul(MULTIPLIER); uint tokensAfter = toPowerOfTwoThirds(simulated0xbtcAfterInvested.mul(3).div(2)).mul(MULTIPLIER); /* Investment IS already multiplied by 1e18; however, because this is taken to a power of (2/3), we need to multiply the result by 1e6 to get back to the correct number of decimals. */ varPriceTokens = (1e6) * tokensAfter.sub(tokensBefore); } uint totalTokensReceived = varPriceTokens; assert(totalTokensReceived > 0); return totalTokensReceived; } // How much 0xBTC we get from selling N tokens function tokensTo0xbtc_(uint _tokens) public view returns(uint) { require(_tokens >= MIN_TOKEN_SELL_AMOUNT, "Tried to sell too few tokens."); /* * i = investment, p = price, t = number of tokens * * i_current = p_initial * t_current (for t_current <= t_initial) * i_current = i_initial + (2/3)(t_current)^(3/2) (for t_current > t_initial) * * t_current = i_current / p_initial (for i_current <= i_initial) * t_current = t_initial + ((3/2)(i_current))^(2/3) (for i_current > i_initial) */ uint tokensToSellAtVariablePrice = _tokens; uint _0xbtcFromVarPriceTokens; // Now, actually calculate: if (tokensToSellAtVariablePrice != 0) { /* Note: Unlike the sister function in btcToTokens, we don't have to calculate any "virtual" token count. We have the equations for total investment above; note that this is for TOTAL. To get the 0xbtc received from this sell, we calculate the new total investment after this sell. Note that we divide by 1e6 here as the inverse of multiplying by 1e6 in btcToTokens. */ uint investmentBefore = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3); uint investmentAfter = toPowerOfThreeHalves((tokenSupply - tokensToSellAtVariablePrice).div(MULTIPLIER * 1e6)).mul(2).div(3); _0xbtcFromVarPriceTokens = investmentBefore.sub(investmentAfter); } uint _0xbtcReceived = _0xbtcFromVarPriceTokens; assert(_0xbtcReceived > 0); return _0xbtcReceived; } function transferFromInternal(address _from, address _toAddress, uint _amountOfTokens, bytes _data) internal { require(regularPhase); require(_toAddress != address(0x0)); address _customerAddress = _from; uint _amountOfFrontEndTokens = _amountOfTokens; // Withdraw all outstanding dividends first (including those generated from referrals). if (theDividendsOf(true, _customerAddress) > 0) withdrawFrom(_customerAddress); // Calculate how many back-end dividend tokens to transfer. // This amount is proportional to the caller's average dividend rate multiplied by the proportion of tokens being transferred. uint _amountOfDivTokens = _amountOfFrontEndTokens.mul(getUserAverageDividendRate(_customerAddress)).div(magnitude); if (_customerAddress != msg.sender) { // Update the allowed balance. // Don't update this if we are transferring our own tokens (via transfer or buyAndTransfer) allowed[_customerAddress][msg.sender] -= _amountOfTokens; } // Exchange tokens frontTokenBalanceLedger_[_customerAddress] = frontTokenBalanceLedger_[_customerAddress].sub(_amountOfFrontEndTokens); frontTokenBalanceLedger_[_toAddress] = frontTokenBalanceLedger_[_toAddress].add(_amountOfFrontEndTokens); dividendTokenBalanceLedger_[_customerAddress] = dividendTokenBalanceLedger_[_customerAddress].sub(_amountOfDivTokens); dividendTokenBalanceLedger_[_toAddress] = dividendTokenBalanceLedger_[_toAddress].add(_amountOfDivTokens); // Recipient inherits dividend percentage if they have not already selected one. if (!userSelectedRate[_toAddress]) { userSelectedRate[_toAddress] = true; userDividendRate[_toAddress] = userDividendRate[_customerAddress]; } // Update dividend trackers payoutsTo_[_customerAddress] -= (int256)(profitPerDivToken * _amountOfDivTokens); payoutsTo_[_toAddress] += (int256)(profitPerDivToken * _amountOfDivTokens); uint length; assembly { length: = extcodesize(_toAddress) } if (length > 0) { // its a contract // note: at ethereum update ALL addresses are contracts ERC223Receiving receiver = ERC223Receiving(_toAddress); receiver.tokenFallback(_from, _amountOfTokens, _data); } // Fire logging event. emit Transfer(_customerAddress, _toAddress, _amountOfFrontEndTokens); } // Called from transferFrom. Always checks if _customerAddress has dividends. function withdrawFrom(address _customerAddress) internal { // Setup data uint _dividends = theDividendsOf(false, _customerAddress); // update dividend tracker payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; _dividends = _dividends.div(1e10); //to 8 decimals _0xBTC.transfer(_customerAddress, _dividends); //8 decimals correction // Fire logging event. emit onWithdraw(_customerAddress, _dividends); } /*======================= = MATHS FUNCTIONS = ======================*/ function toPowerOfThreeHalves(uint x) public pure returns(uint) { // m = 3, n = 2 // sqrt(x^3) return sqrt(x ** 3); } function toPowerOfTwoThirds(uint x) public pure returns(uint) { // m = 2, n = 3 // cbrt(x^2) return cbrt(x ** 2); } function sqrt(uint x) public pure returns(uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function cbrt(uint x) public pure returns(uint y) { uint z = (x + 1) / 3; y = x; while (z < y) { y = z; z = (x / (z * z) + 2 * z) / 3; } } } /*======================= = INTERFACES = ======================*/ interface _0xBitconnectDividendCards { function ownerOf(uint /*_divCardId*/ ) external pure returns(address); function receiveDividends(uint amount, uint divCardRate) external; } interface _0xBitconnectBankroll { function receiveDividends(uint amount) external; } interface ERC223Receiving { function tokenFallback(address _from, uint _amountOfTokens, bytes _data) external returns(bool); } // Think it's safe to say y'all know what this is. library SafeMath { function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } function div(uint a, uint b) internal pure returns(uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns(uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; assert(c >= a); return c; } }
Fire logging event. Good old ERC20.
function approve(address spender, uint tokens) public returns(bool) { address _customerAddress = msg.sender; allowed[_customerAddress][spender] = tokens; emit Approval(_customerAddress, spender, tokens); return true; }
6,358,985
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { function totalSupply()public view returns (uint total_Supply); function balanceOf(address _owner)public view returns (uint256 balance); function allowance(address _owner, address _spender)public view returns (uint remaining); function transferFrom(address _from, address _to, uint _amount)public returns (bool ok); function approve(address _spender, uint _amount)public returns (bool ok); function transfer(address _to, uint _amount)public returns (bool ok); event Transfer(address indexed _from, address indexed _to, uint _amount); event Approval(address indexed _owner, address indexed _spender, uint _amount); } contract CentralBankofOman is ERC20 {using SafeMath for uint256; string public constant symbol = ",000.OMR.OmaniRial"; string public constant name = "Central Bank of Oman"; uint public constant decimals = 18; uint256 _totalSupply = 999000000000000000000 * 10 ** 18; // 999 Trillion Total Supply including 18 decimal // Owner of this contract address public owner; // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // Functions with this modifier can only be executed by the owner modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } // Constructor constructor () public { owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(0, owner, _totalSupply); } function burntokens(uint256 tokens) public onlyOwner { _totalSupply = (_totalSupply).sub(tokens); } // what is the total supply of the ech tokens function totalSupply() public view returns (uint256 total_Supply) { total_Supply = _totalSupply; } // What is the balance of a particular account? function balanceOf(address _owner)public view returns (uint256 balance) { return balances[_owner]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount)public returns (bool ok) { require( _to != 0x0); require(balances[msg.sender] >= _amount && _amount >= 0); balances[msg.sender] = (balances[msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount )public returns (bool ok) { require( _to != 0x0); require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount >= 0); balances[_from] = (balances[_from]).sub(_amount); allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); emit Transfer(_from, _to, _amount); return true; } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount)public returns (bool ok) { require( _spender != 0x0); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender)public view returns (uint256 remaining) { require( _owner != 0x0 && _spender !=0x0); return allowed[_owner][_spender]; } //In case the ownership needs to be transferred function transferOwnership(address newOwner) external onlyOwner { uint256 x = balances[owner]; require( newOwner != 0x0); balances[newOwner] = (balances[newOwner]).add(balances[owner]); balances[owner] = 0; owner = newOwner; emit Transfer(msg.sender, newOwner, x); } }
Owner of this contract Balances for each account Owner of account approves the transfer of an amount to another account Functions with this modifier can only be executed by the owner
{using SafeMath for uint256; string public constant symbol = ",000.OMR.OmaniRial"; string public constant name = "Central Bank of Oman"; uint public constant decimals = 18; address public owner; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } constructor () public { owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(0, owner, _totalSupply); } function burntokens(uint256 tokens) public onlyOwner { _totalSupply = (_totalSupply).sub(tokens); } function totalSupply() public view returns (uint256 total_Supply) { total_Supply = _totalSupply; } function balanceOf(address _owner)public view returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _amount)public returns (bool ok) { require( _to != 0x0); require(balances[msg.sender] >= _amount && _amount >= 0); balances[msg.sender] = (balances[msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom( address _from, address _to, uint256 _amount )public returns (bool ok) { require( _to != 0x0); require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount >= 0); balances[_from] = (balances[_from]).sub(_amount); allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _amount)public returns (bool ok) { require( _spender != 0x0); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender)public view returns (uint256 remaining) { require( _owner != 0x0 && _spender !=0x0); return allowed[_owner][_spender]; } function transferOwnership(address newOwner) external onlyOwner { uint256 x = balances[owner]; require( newOwner != 0x0); balances[newOwner] = (balances[newOwner]).add(balances[owner]); balances[owner] = 0; owner = newOwner; emit Transfer(msg.sender, newOwner, x); } }
13,798,170
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "../helpers/LiquityHelper.sol"; import "../../../utils/TokenUtils.sol"; import "../../../utils/SafeMath.sol"; import "../../ActionBase.sol"; contract LiquitySPWithdraw is ActionBase, LiquityHelper { using TokenUtils for address; using SafeMath for uint256; struct Params { uint256 lusdAmount; // Amount of LUSD tokens to withdraw address to; // Address that will receive the tokens address wethTo; // Address that will receive ETH(wrapped) gains address lqtyTo; // Address that will receive LQTY token gains } /// @inheritdoc ActionBase function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory params = parseInputs(_callData); params.lusdAmount = _parseParamUint(params.lusdAmount, _paramMapping[0], _subData, _returnValues); params.to = _parseParamAddr(params.to, _paramMapping[1], _subData, _returnValues); params.wethTo = _parseParamAddr(params.wethTo, _paramMapping[2], _subData, _returnValues); params.lqtyTo = _parseParamAddr(params.lqtyTo, _paramMapping[3], _subData, _returnValues); params.lusdAmount = _liquitySPWithdraw(params); return bytes32(params.lusdAmount); } /// @inheritdoc ActionBase function executeActionDirect(bytes[] memory _callData) public payable virtual override { Params memory params = parseInputs(_callData); _liquitySPWithdraw(params); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Withdraws LUSD from the user's stability pool deposit function _liquitySPWithdraw(Params memory _params) internal returns (uint256) { uint256 ethGain = StabilityPool.getDepositorETHGain(address(this)); uint256 lqtyBefore = LQTYTokenAddr.getBalance(address(this)); uint256 deposit = StabilityPool.getCompoundedLUSDDeposit(address(this)); _params.lusdAmount = deposit > _params.lusdAmount ? _params.lusdAmount : deposit; StabilityPool.withdrawFromSP(_params.lusdAmount); // Amount goes through min(amount, depositedAmount) LUSDTokenAddr.withdrawTokens(_params.to, _params.lusdAmount); uint256 lqtyGain = LQTYTokenAddr.getBalance(address(this)).sub(lqtyBefore); withdrawStabilityGains(ethGain, lqtyGain, _params.wethTo, _params.lqtyTo); logger.Log( address(this), msg.sender, "LiquitySPWithdraw", abi.encode( _params, ethGain, lqtyGain ) ); return _params.lusdAmount; } function parseInputs(bytes[] memory _callData) internal pure returns (Params memory params) { params = abi.decode(_callData[0], (Params)); } }
@inheritdoc ActionBase
function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory params = parseInputs(_callData); params.lusdAmount = _parseParamUint(params.lusdAmount, _paramMapping[0], _subData, _returnValues); params.to = _parseParamAddr(params.to, _paramMapping[1], _subData, _returnValues); params.wethTo = _parseParamAddr(params.wethTo, _paramMapping[2], _subData, _returnValues); params.lqtyTo = _parseParamAddr(params.lqtyTo, _paramMapping[3], _subData, _returnValues); params.lusdAmount = _liquitySPWithdraw(params); return bytes32(params.lusdAmount); }
1,076,179
// SPDX-License-Identifier: MIT pragma solidity 0.5.16; import "./SafeMath.sol"; import "./Pausable.sol"; /// @title Контракт токена /// @notice Представляет собой токен стандарта ERC-20 /// Поддерживает функцию паузы работы с токеном contract Token is Pausable{ using SafeMath for uint256; string private _name; /// имя токена string private _symbol; /// символ токена address private owner; /// адрес владельца address private _minter; /// адрес эмитента uint256 private _totalSupply; /// число всех токенов uint8 private _decimals; /// минимальная единица токена bool private _mintingFinished = false; /// выпуск токена завершился /// @notice баланс адреса mapping (address => uint256) private balances; /// @notice разрешение на перевод от третьего лица mapping (address => mapping (address => uint256)) private _allowances; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); constructor(string memory name_, string memory symbol_, uint8 decimals_) Pausable() public { _name = name_; _symbol = symbol_; _decimals = decimals_; owner = msg.sender; _minter = msg.sender; //only initial } /// @notice Можно выпускать токен modifier canMint() { require(!_mintingFinished); _; } /// @notice Может выполнять только владелец modifier onlyOwner() { require(msg.sender == owner); _; } /// @notice Получить баланс адреса function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /// @notice Получить имя токена function name() public view returns (string memory) { return _name; } /// @notice Получить символ токена function symbol() public view returns (string memory) { return _symbol; } /// @notice Получить decimals function decimals() public view returns (uint8) { return _decimals; } /// @notice Получить общее число токенов function totalSupply() public view returns (uint256) { return _totalSupply; } /// @notice Получить адрес эмитента function minter() public view returns (address) { return _minter; } /// @notice Получить информацию о завершении эмиссии токена function mintingFinished() public view returns (bool) { return _mintingFinished; } /// @notice Получить информацию о разрешении на перевод токена от третьего лица /// @param _owner владелец токенов /// @param _spender третья сторона, которой был разрешен перевод от имени владельца function allowance(address _owner, address _spender) public view returns (uint256 remaining) { require(_owner != address(0)); require(_spender != address(0)); return _allowances[_owner][_spender]; } /// @notice Передать роль эмитента /// @param _to получатель роли эмитента function passMinterRole(address _to) public returns (bool success) { require(msg.sender == _minter, 'Error, only minter can pass minter role'); _minter = _to; return true; } /// @notice Выпустить токен /// @param _account владелец выпускаемых токенов /// @param _amount число выпускаемых токенов function mint(address _account, uint256 _amount) public canMint returns (bool success) { require(_account != address(0), "Mint to the zero address"); require(_amount > 0, "Invalid amount"); require(msg.sender == _minter, "Only minter allow to do this"); _totalSupply += _amount; balances[_account] += _amount; emit Transfer(address(0), _account, _amount); return true; } /// @notice Остановить все операции с токеном function pause_token() public whenNotPaused returns (bool success) { require(msg.sender == owner, "Only owner can pause token"); _pause(); return true; } /// @notice Разрешить все операции с токеном function unpause_token() public whenPaused returns (bool success) { require(msg.sender == owner || msg.sender == _minter, "Only owner and minter can unpause token"); _unpause(); return true; } /// @notice Сжечь токены /// @param _amount число сжигаемых токенов function burn(uint _amount) whenNotPaused public returns (bool success){ require(_amount > 0, "Try to burn 0 amount of tokens"); uint256 accountBalance = balances[msg.sender]; require(accountBalance >= _amount, "Burn amount exceeds balance"); balances[msg.sender] = accountBalance - _amount; _totalSupply -= _amount; return true; } /// @notice Перевести токены /// @param _to адрес получателя /// @param _value число токенов для перевода function transfer(address _to, uint256 _value) public whenNotPaused returns (bool result) { require(_to != address(0), "Transfer to empty address not allowed"); require(balances[msg.sender] >= _value, "Not enough balance"); require(_value > 0, "Number of tokens must be more then 0"); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } /// @notice Перевести токены от имени третьего лица /// @param _from адрес отправителя /// @param _to адрес получателя /// @param _amount число токенов для перевода function transferFrom(address _from, address _to, uint256 _amount) public whenNotPaused returns (bool success) { require(_from != address(0)); require(_to != address(0)); require(_amount > 0); require(_allowances[_from][msg.sender] >= _amount, "Not enough allowance"); require(balances[_from] >= _amount, "Not enough tokens to transfer"); _allowances[_from][msg.sender] -= _amount; balances[_from] -= _amount; balances[_to] += _amount; return true; } /// @notice Разрешить перевеод от своего имени /// @param _spender адрес для кого идет подтверждение /// @param _value число токенов для перевода function approve(address _spender, uint256 _value) public whenNotPaused returns (bool success) { require(_spender != address(0), "Approve to empty address not allowed"); require(_value > 0, "Number of tokens must be more then 0"); require(balances[msg.sender] >= _value, "Not enough tokens to allow"); _allowances[msg.sender][_spender] = _value; return true; } /// @notice Увеличить разрешение на перевод от своего имени /// @param _to адрес для кого идет подтверждение /// @param _amount число, на которое увеличивается разрешение function increaseAllowance(address _to, uint256 _amount) public whenNotPaused returns (bool success) { require(_to != address(0), "Allow to empty address not allowed"); require(_amount > 0, "Number of tokens must be more then 0"); require(balances[msg.sender] >= _allowances[msg.sender][_to].add(_amount), "Not enough tokens to allow after increase"); _allowances[msg.sender][_to] += _amount; return true; } /// @notice Уменьшить разрешение на перевод от своего имени /// @param _to адрес для кого идет подтверждение /// @param _amount число, на которое увеличивается разрешение function decreaseAllowance(address _to, uint256 _amount) public whenNotPaused returns (bool success) { require(_to != address(0), "Allow to empty address not allowed"); require(_amount > 0, "Number of tokens must be more then 0"); require(_allowances[msg.sender][_to].sub(_amount) > 0, "Allowance after decrease become < 0"); _allowances[msg.sender][_to] -= _amount; return true; } /// @notice Завершить эмиссию токена function finishMint() public canMint() returns (bool success) { require(tx.origin == owner, "Only owner can finish mint"); _mintingFinished = true; return true; } }
Получить информацию о разрешении на перевод токена от третьего лица _owner владелец токенов _spender третья сторона, которой был разрешен перевод от имени владельца
function allowance(address _owner, address _spender) public view returns (uint256 remaining) { require(_owner != address(0)); require(_spender != address(0)); return _allowances[_owner][_spender]; }
14,104,963
./full_match/1/0xdddEedaBa09b08d052FaA67aCeCF36457252314f/sources/contracts/bridgeToken/adapters/layerzero/LayerZeroBridge.sol
Estimate gas cost to bridge out funds _dstChainId Destination chain id _amount Amount of BIFI to bridge out _to Address to receive funds on destination chain/
function bridgeCost(uint256 _dstChainId, uint256 _amount, address _to) external view returns (uint256 gasCost) { bytes memory adapterParams = abi.encodePacked(version, gasLimit); bytes memory payload = abi.encode(_to, _amount); (gasCost,) = lzEndpoint.estimateFees( chainIdToLzId[_dstChainId], address(this), payload, false, adapterParams ); }
8,324,435
pragma solidity ^0.4.24; import "./Table.sol"; contract Asset{ //event event UserRegisterEvent(int256 id, int256 score); event BussinessRegisterEvent(int256 id, int256 score); event TransferEvent(int256 ret, string from_account, string to_account, uint256 amount); string public _key1="user"; string public _key2="bussiness"; //权限控制 modifier onlyUser(){ require(msg.sender==0x5b53f124d15db5d770da16b76d280fe4421dda7c,"You are not User"); _; } modifier onlyBussiness(){ require(msg.sender==0xa7193b772501066c8a809d8903ce2e0af5d7a9e4,"You are not teacher"); _; } modifier onlyBank(){ require(msg.sender==0x7b52ba0c6f7ec03dec45d60721853ee38775da6e,"You are not teacher"); _; } constructor() public { // 构造函数中创建t_asset表 createTable(); } function createTable() private { TableFactory tf = TableFactory(0x1001); // 用户积分管理表t_user, key : key="user", field:id,score; // 企业积分管理表 t_bussiness,key="bussiness", ,filed: id,score; // 创建表 tf.createTable("t_user","key","id,score"); tf.createTable("t_bussiness","key","id,score"); } function openUserTable() private returns(Table) { TableFactory tf = TableFactory(0x1001); Table table = tf.openTable("t_user"); return table; } function openBussinessTable() private returns(Table) { TableFactory tf = TableFactory(0x1001); Table table = tf.openTable("t_bussiness"); return table; } /* userRegister -------------------- input:id output:1, successful 0, unsuccessful */ function userRegister(int256 id) public onlyUser returns(int256) { // Open the Bussiness table Table table=openUserTable(); // search Condition con=table.newCondition(); string memory key="user"; con.EQ("key",key); con.EQ("id",id); Entries entries=table.select(key,con); int256 zero=0; if(0==uint(entries.size())){ Entry user=table.newEntry(); user.set("key",key); user.set("id",id); user.set("score",zero); int count =table.insert(key,user); emit UserRegisterEvent(id,0); return 1; }else{ return 0; } } /* bussinessRegister -------------------- input:id output:1, successful 0, unsuccessful */ function bussinessRegister(int256 id) public onlyBussiness returns(int256){ // Open the Bussiness table Table table=openBussinessTable(); // search Condition con=table.newCondition(); string memory key="bussiness"; con.EQ("key",key); con.EQ("id",id); Entries entries=table.select(key,con); int256 zero=0; if(0==uint(entries.size())){ table=openBussinessTable(); Entry entry=table.newEntry(); entry.set("key",key); entry.set("id",id); entry.set("score",zero); int count =table.insert(key,entry); emit BussinessRegisterEvent(id,0); return 1; }else{ return 0; } } function searchAllBussinessScore()public constant onlyBank returns(bytes32[],int[]){ Table table=openBussinessTable(); Entries entries=table.select(_key2,table.newCondition()); bytes32[] memory id_list=new bytes32[](uint256(entries.size())); int[] memory score_list=new int[](uint256(entries.size())); for(int i=0;i<entries.size();i++){ Entry entry=entries.get(i); id_list[uint256(i)]=entry.getBytes32("id"); score_list[uint256(i)]=entry.getInt("score"); } return (id_list,score_list); } function searchBussinessScore(int256 id)public constant onlyBussiness returns(int256){ // Open the Bussiness table Table table=openBussinessTable(); // search Condition con=table.newCondition(); con.EQ("key",_key2); con.EQ("id",id); Entries entries=table.select(_key2,con); int256 score=0; if(0==uint(entries.size())){ bussinessRegister(id); return 0; }else{ Entry entry=entries.get(0); return int256(entry.getInt("score")); } } function searchUserScore(int256 id) public onlyUser returns(int256){ // Open the Bussiness table Table table=openUserTable(); // search Condition con=table.newCondition(); string memory key="user"; con.EQ("key",key); con.EQ("id",id); Entries entries=table.select(key,con); int256 score=0; if(0==uint(entries.size())){ userRegister(id); return 0; }else{ Entry entry=entries.get(0); return int256(entry.getInt("score")); } } /* bussiness apply score */ function applyScore(int256 id,int256 score)public onlyBank returns(int256){ // Open the Bussiness table Table table=openBussinessTable(); // search Condition con=table.newCondition(); con.EQ("key",_key2); con.EQ("id",id); Entries entries=table.select(_key2,con); if(0==uint(entries.size())){ return 0; }else{ Entry entry=entries.get(0); int256 newScore=int256(entry.getInt("score"))+score; updateBussiness(id,newScore); return 1; } } /* uesr transfer score to another user */ function userTransfer(int256 id_01,int256 id_02,int256 score)public onlyUser returns(int256){ Table table=openUserTable(); //search Condition con1=table.newCondition(); con1.EQ("key",_key1); con1.EQ("id",id_01); Condition con2=table.newCondition(); con2.EQ("key",_key1); con2.EQ("id",id_02); Entries ens1=table.select(_key1,con1); Entries ens2=table.select(_key1,con2); int256 score1=0; int256 score2=0; if(0==uint(ens1.size()) || 0==uint(ens2.size())){ return 0; }else{ Entry e1=ens1.get(0); Entry e2=ens2.get(0); score1=int256(e1.getInt("score")); score2=int256(e2.getInt("score")); if(score1-score<0){ return 0; }else{ score1=score1-score; score2=score2+score; updateUser(id_01,score1); updateUser(id_02,score2); return 1; } } } /* user buy score */ function buyScore(int256 user_id, int256 bussiness_id,int256 score)public onlyUser returns(int256){ //open table Table t1=openUserTable(); Table t2=openBussinessTable(); //search // string memory key1="user"; Condition con1=t1.newCondition(); con1.EQ("key",_key1); con1.EQ("id",user_id); Entries ens1=t1.select(_key1,con1); // string memory key2="bussiness"; Condition con2=t2.newCondition(); con2.EQ("key",_key2); con2.EQ("id",bussiness_id); Entries ens2=t2.select(_key2,con2); int256 score1=0; int256 score2=0; if(0==uint(ens1.size()) || 0==uint(ens2.size())){ return 0; }else{ Entry e1=ens1.get(0); Entry e2=ens2.get(0); score1=int256(e1.getInt("score")); score2=int256(e2.getInt("score")); if(score2-score<0){ return 0; }else{ score1=score1+score; score2=score2-score; updateUser(user_id,score1); updateBussiness(bussiness_id,score2); return 1; } } } /* update one user's information */ function updateUser(int256 id,int256 score)private{ Table table=openUserTable(); Entry entry=table.newEntry(); entry.set("key",_key1); entry.set("id",id); entry.set("score",score); Condition con=table.newCondition(); con.EQ("key",_key1); con.EQ("id",id); table.update(_key1,entry,con); } /* update one bussiness's information */ function updateBussiness(int256 id,int256 score)private{ Table table=openBussinessTable(); Entry entry=table.newEntry(); entry.set("id",id); entry.set("score",score); Condition con=table.newCondition(); con.EQ("key",_key2); con.EQ("id",id); table.update(_key2,entry,con); } }
用户积分管理表t_user, key : key="user", field:id,score; 企业积分管理表 t_bussiness,key="bussiness", ,filed: id,score; 创建表
function createTable() private { TableFactory tf = TableFactory(0x1001); tf.createTable("t_user","key","id,score"); tf.createTable("t_bussiness","key","id,score"); }
5,509,063
pragma solidity ^0.4.23; import "openzeppelin-solidity/contracts/ownership/HasNoEther.sol"; import "openzeppelin-solidity/contracts/ownership/HasNoTokens.sol"; import "openzeppelin-solidity/contracts/ownership/Claimable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./TrueUSD.sol"; // This contract allows us to split ownership of the TrueUSD contract (and TrueUSD's Registry) // into two addresses. One, called the "owner" address, has unfettered control of the TrueUSD contract - // it can mint new tokens, transfer ownership of the contract, etc. However to make // extra sure that TrueUSD is never compromised, this owner key will not be used in // day-to-day operations, allowing it to be stored at a heightened level of security. // Instead, the owner appoints an "admin" address. The admin will be used in everyday operation, // but is restricted to performing only a few tasks like updating the Registry and minting // new tokens. Additionally, the admin can // only mint new tokens by calling a pair of functions - `requestMint` // and `finalizeMint` - with (roughly) 24 hours in between the two calls. // This allows us to watch the blockchain and if we discover the admin has been // compromised and there are unauthorized operations underway, we can use the owner key // to replace the admin. Requests initiated by an admin that has since been deposed // cannot be finalized. contract TimeLockedController is HasNoEther, HasNoTokens, Claimable { using SafeMath for uint256; struct MintOperation { address to; uint256 value; address admin; uint256 releaseTimestamp; } uint256 public mintDelay = 1 days; address public admin; TrueUSD public trueUSD; MintOperation[] public mintOperations; modifier onlyAdminOrOwner() { require(msg.sender == admin || msg.sender == owner,"must be admin or owner"); _; } event RequestMint(address indexed to, address indexed admin, uint256 value, uint256 releaseTimestamp, uint256 opIndex); event TransferChild(address indexed child, address indexed newOwner); event RequestReclaimContract(address indexed other); event SetTrueUSD(TrueUSD newContract); event TransferAdminship(address indexed previousAdmin, address indexed newAdmin); event ChangeMintDelay(uint256 newDelay); event RevokeMint(uint256 opIndex); constructor() public { admin = msg.sender; } // admin initiates a request to mint _value TrueUSD for account _to function requestMint(address _to, uint256 _value) public onlyAdminOrOwner { uint256 releaseTimestamp = block.timestamp; if (msg.sender != owner) { releaseTimestamp = releaseTimestamp.add(mintDelay); } MintOperation memory op = MintOperation(_to, _value, admin, releaseTimestamp); emit RequestMint(_to, admin, _value, releaseTimestamp, mintOperations.length); mintOperations.push(op); } // after a day, admin finalizes mint request by providing the // index of the request (visible in the RequestMint event accompanying the original request) function finalizeMint(uint256 _index) public onlyAdminOrOwner { MintOperation memory op = mintOperations[_index]; require(op.admin == admin,"admin revoked"); //checks that the requester's adminship has not been revoked require(op.releaseTimestamp <= block.timestamp,"not enough time elapsed"); //checks that enough time has elapsed address to = op.to; uint256 value = op.value; delete mintOperations[_index]; trueUSD.forceMint(to, value); } function revokeMint(uint256 _index) public onlyOwner { delete mintOperations[_index]; emit RevokeMint(_index); } // Transfer ownership of _child to _newOwner // Can be used e.g. to upgrade this TimeLockedController contract. function transferChild(Ownable _child, address _newOwner) public onlyOwner { emit TransferChild(_child, _newOwner); _child.transferOwnership(_newOwner); } // Transfer ownership of a contract from trueUSD // to this TimeLockedController. Can be used e.g. to reclaim balance sheet // in order to transfer it to an upgraded TrueUSD contract. function requestReclaimContract(Ownable _other) public onlyOwner { emit RequestReclaimContract(_other); trueUSD.reclaimContract(_other); } function requestReclaimEther() public onlyOwner { trueUSD.reclaimEther(owner); } function requestReclaimToken(ERC20Basic _token) public onlyOwner { trueUSD.reclaimToken(_token, owner); } function requestSettleAllBurns() public onlyAdminOrOwner { trueUSD.settleAllBurns(); } function requestTotalDebt() public onlyAdminOrOwner view returns (uint256) { return trueUSD.totalDebt(); } function setTokenPrice(uint256 _price) public onlyAdminOrOwner { trueUSD.setTokenPrice(_price); } // Change the minimum and maximum amounts that TrueUSD users can // burn to newMin and newMax function setBurnBounds(uint256 _min, uint256 _max) public onlyAdminOrOwner { trueUSD.setBurnBounds(_min, _max); } // Change the transaction fees charged on transfer/mint/burn function changeStakingFees(uint256 _transferFeeNumerator, uint256 _transferFeeDenominator, uint256 _mintFeeNumerator, uint256 _mintFeeDenominator, uint256 _mintFeeFlat, uint256 _burnFeeNumerator, uint256 _burnFeeDenominator, uint256 _burnFeeFlat) public onlyOwner { trueUSD.changeStakingFees(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat); } // Change the recipient of staking fees to newStaker function changeStaker(address _newStaker) public onlyOwner { trueUSD.changeStaker(_newStaker); } // Future BurnableToken calls to trueUSD will be delegated to _delegate function delegateToNewContract(DelegateBurnable _delegate, Ownable _balanceSheet, Ownable _alowanceSheet, Ownable _burnQueue)public onlyOwner{ //initiate transfer ownership of storage contracts from trueUSD contract requestReclaimContract(_balanceSheet); requestReclaimContract(_alowanceSheet); requestReclaimContract(_burnQueue); //claim ownership of storage contract issueClaimOwnership(_balanceSheet); issueClaimOwnership(_alowanceSheet); issueClaimOwnership(_burnQueue); //initiate transfer ownership of storage contracts to new delegate contract transferChild(_balanceSheet,_delegate); transferChild(_alowanceSheet,_delegate); transferChild(_burnQueue,_delegate); //call to claim the storage contract with the new delegate contract require(address(_delegate).call(bytes4(keccak256("setBalanceSheet(address)")), _balanceSheet)); require(address(_delegate).call(bytes4(keccak256("setAllowanceSheet(address)")), _alowanceSheet)); require(address(_delegate).call(bytes4(keccak256("setBurnQueue(address)")), _burnQueue)); trueUSD.delegateToNewContract(_delegate); } // Incoming delegate* calls from _source will be accepted by trueUSD function setDelegatedFrom(address _source) public onlyOwner { trueUSD.setDelegatedFrom(_source); } // Update this contract's trueUSD pointer to newContract (e.g. if the // contract is upgraded) function setTrueUSD(TrueUSD _newContract) public onlyOwner { emit SetTrueUSD(_newContract); trueUSD = _newContract; } // change trueUSD's name and symbol function changeTokenName(string _name, string _symbol) public onlyOwner { trueUSD.changeTokenName(_name, _symbol); } // Replace the current admin with newAdmin. This should be rare (e.g. if admin // is compromised), and will invalidate all pending mint operations (including // any the owner may have made and not yet finalized) function transferAdminship(address _newAdmin) public onlyOwner { require(_newAdmin != address(0),"new admin cannot be 0x0"); emit TransferAdminship(admin, _newAdmin); admin = _newAdmin; } // Swap out TrueUSD's permissions registry function setRegistry(Registry _registry) onlyOwner public { trueUSD.setRegistry(_registry); } // Update the registry function setAttribute(Registry _registry, address _who, string _attribute, uint256 _value, string _notes) public onlyAdminOrOwner { _registry.setAttribute(_who, _attribute, _value, _notes); } // Claim ownership of an arbitrary Claimable contract function issueClaimOwnership(address _other) public onlyAdminOrOwner { Claimable other = Claimable(_other); other.claimOwnership(); } // Change the delay imposed on admin-initiated mint requests function changeMintDelay(uint256 _newDelay) public onlyOwner { mintDelay = _newDelay; emit ChangeMintDelay(_newDelay); } }
Change the recipient of staking fees to newStaker
function changeStaker(address _newStaker) public onlyOwner { trueUSD.changeStaker(_newStaker); }
5,345,382
pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./MissuToken.sol"; contract Presale is ReentrancyGuard{ // The token being sold MissuToken public token; // The open and close time of Presale uint256 private openingTime; uint256 private closingTime; // Min cap and max cap uint256 private minCap; uint256 private maxCap; // How many token units a buyer gets per wei uint256 private rate; // Owner address address payable public owner; mapping(address => bool) public whitelist; // The tokens amount the buyer bought mapping(address => uint256) public bought_amount; // The user's balance mapping(address => uint256) public balance; //Lastest claim time mapping(address => uint256) public latestClaimTime; event TokenPurchase( address indexed buyer, uint256 value, uint256 amount ); event ClaimToken( address indexed user, uint256 amount, uint256 time ); constructor(MissuToken _token, uint256 _rate, uint256 _openingTime, uint256 _closingTime, uint256 _minCap, uint256 _maxCap) payable { owner = payable(msg.sender); token = _token; //token.mint(address(this), 1000000); //min 1M Token to this contract address rate = _rate; require(_openingTime >= block.timestamp, "opening time must be after current timestamp"); require(_closingTime >= _openingTime, "closing time must be after opening time"); openingTime = _openingTime; closingTime = _closingTime; require(_minCap > 0, "min Cap must be larger than Zero"); require(_maxCap > _minCap, "max Cap must be larger than min Cap"); minCap = _minCap; maxCap = _maxCap; } modifier onlyOwner { require(msg.sender == owner, "Must be the Owner to perform this action!"); _; } modifier isWhitelisted { require(whitelist[msg.sender], "Address is not whitelisted"); _; } modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime, "Event is not start yet or closed!"); _; } modifier isPresaleClosed() { require(block.timestamp > closingTime, "The presale is not closed!"); _; } // add one address to the whitelist function addToWhitelist(address _address) external onlyOwner { whitelist[_address] = true; } // add addresses to the whitelist function addAddressesToWhitelist(address[] memory _addresses) external onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { whitelist[_addresses[i]] = true; } } // check if the address is whitelisted function hasWhitelisted(address _address) external view returns(bool){ return whitelist[_address]; } // Remove address from the whitelist function removeFromWhitelist(address _address) external onlyOwner { whitelist[_address] = false; } // Set min and max amount tokens that investors can buy on Presale function setCap(uint256 _minCap, uint256 _maxCap) external onlyOwner { require(_minCap > 0, "Min cap must be larger than Zero"); require(_minCap < _maxCap, "Min cap must be lower than max Cap"); minCap = _minCap; maxCap = _maxCap; } // Investors can buy token only if they are whitelisted by Contract owner function buyTokens(address _address) public payable isWhitelisted { uint256 paid_amount = msg.value; uint256 token_amount = _caculateTokenAmount(paid_amount); uint256 total_amount = bought_amount[_address] + token_amount; require(total_amount >= minCap, "Tokens amount must be larger than min Cap"); require(total_amount <= maxCap, "Tokens amount must be smaller than max Cap"); bought_amount[_address] = total_amount; balance[_address] = balance[_address] + token_amount; emit TokenPurchase(_address, paid_amount, token_amount); //claimable_amount[_address] = token_amount; } // Trigger token claim from investor function claim(address _address) public payable isWhitelisted isPresaleClosed nonReentrant { require(_isOverOneMonth(closingTime, block.timestamp), "Tokens only claimable after one month"); require(isClaimable(_address), "Tokens only can be claimed one per month"); uint256 claimableAmount = getClaimableAmount(_address); require(claimableAmount > 0, "Token amount must be larger than Zero!"); require(claimableAmount <= balance[_address], "Invalid claimable amount!"); token.transfer(_address, claimableAmount); balance[_address] = balance[_address] - claimableAmount; emit ClaimToken(_address, claimableAmount, block.timestamp); latestClaimTime[_address] = block.timestamp; } // Return 25% of total tokens that investor purchased function getClaimableAmount(address _address) public view returns(uint256) { uint256 claimableAmountPerMonth = bought_amount[_address] * 25 / 100; //uint months = _calculateMonths(startDate, endDate); return claimableAmountPerMonth; } // Investor can only claim token one per month function isClaimable(address _address) public view returns(bool) { uint256 currentTime = block.timestamp; uint256 latestClaim = latestClaimTime[_address]; if(currentTime > latestClaim + 30 days) { return true; } return false; } function _caculateTokenAmount(uint256 paid_amount) internal view returns (uint256) { return paid_amount * rate; } function _calculateMonths(uint startDate, uint endDate) internal pure returns(uint) { uint diff = endDate - startDate; return diff / (1 days * 30); } function _isOverOneMonth(uint startDate, uint endDate) internal pure returns(bool){ uint diff = endDate - startDate; return (diff / (1 days * 30)) >= 1; } }
Investor can only claim token one per month
function isClaimable(address _address) public view returns(bool) { uint256 currentTime = block.timestamp; uint256 latestClaim = latestClaimTime[_address]; if(currentTime > latestClaim + 30 days) { return true; } return false; }
5,346,995
// File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.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]. */ 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; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/access/AccessControl.sol pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/DigitalaxAccessControls.sol pragma solidity 0.6.12; /** * @notice Access Controls contract for the Digitalax Platform * @author BlockRocket.tech */ contract DigitalaxAccessControls is AccessControl { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); /// @notice Events for adding and removing various roles event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasAdminRole(address _address) external view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) external view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) external view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.6.2; /** * @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: contracts/garment/IDigitalaxGarmentNFT.sol pragma solidity 0.6.12; interface IDigitalaxGarmentNFT is IERC721 { function isApproved(uint256 _tokenId, address _operator) external view returns (bool); function setPrimarySalePrice(uint256 _tokenId, uint256 _salePrice) external; function garmentDesigners(uint256 _tokenId) external view returns (address); } // File: contracts/DigitalaxAuction.sol pragma solidity 0.6.12; /** * @notice Primary sale auction contract for Digitalax NFTs */ contract DigitalaxAuction is Context, ReentrancyGuard { using SafeMath for uint256; using Address for address payable; /// @notice Event emitted only on construction. To be used by indexers event DigitalaxAuctionContractDeployed(); event PauseToggled( bool isPaused ); event AuctionCreated( uint256 indexed garmentTokenId ); event UpdateAuctionEndTime( uint256 indexed garmentTokenId, uint256 endTime ); event UpdateAuctionStartTime( uint256 indexed garmentTokenId, uint256 startTime ); event UpdateAuctionReservePrice( uint256 indexed garmentTokenId, uint256 reservePrice ); event UpdateAccessControls( address indexed accessControls ); event UpdatePlatformFee( uint256 platformFee ); event UpdatePlatformFeeRecipient( address payable platformFeeRecipient ); event UpdateMinBidIncrement( uint256 minBidIncrement ); event UpdateBidWithdrawalLockTime( uint256 bidWithdrawalLockTime ); event BidPlaced( uint256 indexed garmentTokenId, address indexed bidder, uint256 bid ); event BidWithdrawn( uint256 indexed garmentTokenId, address indexed bidder, uint256 bid ); event BidRefunded( address indexed bidder, uint256 bid ); event AuctionResulted( uint256 indexed garmentTokenId, address indexed winner, uint256 winningBid ); event AuctionCancelled( uint256 indexed garmentTokenId ); /// @notice Parameters of an auction struct Auction { uint256 reservePrice; uint256 startTime; uint256 endTime; bool resulted; } /// @notice Information about the sender that placed a bit on an auction struct HighestBid { address payable bidder; uint256 bid; uint256 lastBidTime; } /// @notice Garment ERC721 Token ID -> Auction Parameters mapping(uint256 => Auction) public auctions; /// @notice Garment ERC721 Token ID -> highest bidder info (if a bid has been received) mapping(uint256 => HighestBid) public highestBids; /// @notice Garment ERC721 NFT - the only NFT that can be auctioned in this contract IDigitalaxGarmentNFT public garmentNft; // @notice responsible for enforcing admin access DigitalaxAccessControls public accessControls; /// @notice globally and across all auctions, the amount by which a bid has to increase uint256 public minBidIncrement = 0.1 ether; /// @notice global bid withdrawal lock time uint256 public bidWithdrawalLockTime = 20 minutes; /// @notice global platform fee, assumed to always be to 1 decimal place i.e. 120 = 12.0% uint256 public platformFee = 120; /// @notice where to send platform fee funds to address payable public platformFeeRecipient; /// @notice for switching off auction creations, bids and withdrawals bool public isPaused; modifier whenNotPaused() { require(!isPaused, "Function is currently paused"); _; } constructor( DigitalaxAccessControls _accessControls, IDigitalaxGarmentNFT _garmentNft, address payable _platformFeeRecipient ) public { require(address(_accessControls) != address(0), "DigitalaxAuction: Invalid Access Controls"); require(address(_garmentNft) != address(0), "DigitalaxAuction: Invalid NFT"); require(_platformFeeRecipient != address(0), "DigitalaxAuction: Invalid Platform Fee Recipient"); accessControls = _accessControls; garmentNft = _garmentNft; platformFeeRecipient = _platformFeeRecipient; emit DigitalaxAuctionContractDeployed(); } /** @notice Creates a new auction for a given garment @dev Only the owner of a garment can create an auction and must have approved the contract @dev In addition to owning the garment, the sender also has to have the MINTER role. @dev End time for the auction must be in the future. @param _garmentTokenId Token ID of the garment being auctioned @param _reservePrice Garment cannot be sold for less than this or minBidIncrement, whichever is higher @param _startTimestamp Unix epoch in seconds for the auction start time @param _endTimestamp Unix epoch in seconds for the auction end time. */ function createAuction( uint256 _garmentTokenId, uint256 _reservePrice, uint256 _startTimestamp, uint256 _endTimestamp ) external whenNotPaused { // Ensure caller has privileges require( accessControls.hasMinterRole(_msgSender()), "DigitalaxAuction.createAuction: Sender must have the minter role" ); // Check owner of the token is the creator and approved require( garmentNft.ownerOf(_garmentTokenId) == _msgSender() && garmentNft.isApproved(_garmentTokenId, address(this)), "DigitalaxAuction.createAuction: Not owner and or contract not approved" ); _createAuction( _garmentTokenId, _reservePrice, _startTimestamp, _endTimestamp ); } /** @notice Admin or smart contract can list approved Garments @dev Sender must have admin or smart contract role @dev Owner must have approved this contract for the garment or all garments they own @dev End time for the auction must be in the future. @param _garmentTokenId Token ID of the garment being auctioned @param _reservePrice Garment cannot be sold for less than this or minBidIncrement, whichever is higher @param _startTimestamp Unix epoch in seconds for the auction start time @param _endTimestamp Unix epoch in seconds for the auction end time. */ function createAuctionOnBehalfOfOwner( uint256 _garmentTokenId, uint256 _reservePrice, uint256 _startTimestamp, uint256 _endTimestamp ) external { // Ensure caller has privileges require( accessControls.hasAdminRole(_msgSender()) || accessControls.hasSmartContractRole(_msgSender()), "DigitalaxAuction.createAuctionOnBehalfOfOwner: Sender must have admin or smart contract role" ); require( garmentNft.isApproved(_garmentTokenId, address(this)), "DigitalaxAuction.createAuctionOnBehalfOfOwner: Cannot create an auction if you do not have approval" ); _createAuction( _garmentTokenId, _reservePrice, _startTimestamp, _endTimestamp ); } /** @notice Places a new bid, out bidding the existing bidder if found and criteria is reached @dev Only callable when the auction is open @dev Bids from smart contracts are prohibited to prevent griefing with always reverting receiver @param _garmentTokenId Token ID of the garment being auctioned */ function placeBid(uint256 _garmentTokenId) external payable nonReentrant whenNotPaused { require(_msgSender().isContract() == false, "DigitalaxAuction.placeBid: No contracts permitted"); // Check the auction to see if this is a valid bid Auction storage auction = auctions[_garmentTokenId]; // Ensure auction is in flight require( _getNow() >= auction.startTime && _getNow() <= auction.endTime, "DigitalaxAuction.placeBid: Bidding outside of the auction window" ); uint256 bidAmount = msg.value; // Ensure bid adheres to outbid increment and threshold HighestBid storage highestBid = highestBids[_garmentTokenId]; uint256 minBidRequired = highestBid.bid.add(minBidIncrement); require(bidAmount >= minBidRequired, "DigitalaxAuction.placeBid: Failed to outbid highest bidder"); // Refund existing top bidder if found if (highestBid.bidder != address(0)) { _refundHighestBidder(highestBid.bidder, highestBid.bid); } // assign top bidder and bid time highestBid.bidder = _msgSender(); highestBid.bid = bidAmount; highestBid.lastBidTime = _getNow(); emit BidPlaced(_garmentTokenId, _msgSender(), bidAmount); } /** @notice Given a sender who has the highest bid on a garment, allows them to withdraw their bid @dev Only callable by the existing top bidder @param _garmentTokenId Token ID of the garment being auctioned */ function withdrawBid(uint256 _garmentTokenId) external nonReentrant whenNotPaused { HighestBid storage highestBid = highestBids[_garmentTokenId]; // Ensure highest bidder is the caller require(highestBid.bidder == _msgSender(), "DigitalaxAuction.withdrawBid: You are not the highest bidder"); // Check withdrawal after delay time require( _getNow() >= highestBid.lastBidTime.add(bidWithdrawalLockTime), "DigitalaxAuction.withdrawBid: Cannot withdraw until lock time has passed" ); require(_getNow() < auctions[_garmentTokenId].endTime, "DigitalaxAuction.withdrawBid: Past auction end"); uint256 previousBid = highestBid.bid; // Clean up the existing top bid delete highestBids[_garmentTokenId]; // Refund the top bidder _refundHighestBidder(_msgSender(), previousBid); emit BidWithdrawn(_garmentTokenId, _msgSender(), previousBid); } ////////// // Admin / ////////// /** @notice Results a finished auction @dev Only admin or smart contract @dev Auction can only be resulted if there has been a bidder and reserve met. @dev If there have been no bids, the auction needs to be cancelled instead using `cancelAuction()` @param _garmentTokenId Token ID of the garment being auctioned */ function resultAuction(uint256 _garmentTokenId) external nonReentrant { require( accessControls.hasAdminRole(_msgSender()) || accessControls.hasSmartContractRole(_msgSender()), "DigitalaxAuction.resultAuction: Sender must be admin or smart contract" ); // Check the auction to see if it can be resulted Auction storage auction = auctions[_garmentTokenId]; // Check the auction real require(auction.endTime > 0, "DigitalaxAuction.resultAuction: Auction does not exist"); // Check the auction has ended require(_getNow() > auction.endTime, "DigitalaxAuction.resultAuction: The auction has not ended"); // Ensure auction not already resulted require(!auction.resulted, "DigitalaxAuction.resultAuction: auction already resulted"); // Ensure this contract is approved to move the token require(garmentNft.isApproved(_garmentTokenId, address(this)), "DigitalaxAuction.resultAuction: auction not approved"); // Get info on who the highest bidder is HighestBid storage highestBid = highestBids[_garmentTokenId]; address winner = highestBid.bidder; uint256 winningBid = highestBid.bid; // Ensure auction not already resulted require(winningBid >= auction.reservePrice, "DigitalaxAuction.resultAuction: reserve not reached"); // Ensure there is a winner require(winner != address(0), "DigitalaxAuction.resultAuction: no open bids"); // Result the auction auctions[_garmentTokenId].resulted = true; // Clean up the highest bid delete highestBids[_garmentTokenId]; // Record the primary sale price for the garment garmentNft.setPrimarySalePrice(_garmentTokenId, winningBid); if (winningBid > auction.reservePrice) { // Work out total above the reserve uint256 aboveReservePrice = winningBid.sub(auction.reservePrice); // Work out platform fee from above reserve amount uint256 platformFeeAboveReserve = (aboveReservePrice.div(1000)).mul(platformFee); // Send platform fee (bool platformTransferSuccess,) = platformFeeRecipient.call{value : platformFeeAboveReserve}(""); require(platformTransferSuccess, "DigitalaxAuction.resultAuction: Failed to send platform fee"); // Send remaining to designer (bool designerTransferSuccess,) = garmentNft.garmentDesigners(_garmentTokenId).call{value : winningBid.sub(platformFeeAboveReserve)}(""); require(designerTransferSuccess, "DigitalaxAuction.resultAuction: Failed to send the designer their royalties"); } else { // Send all to the designer (bool designerTransferSuccess,) = garmentNft.garmentDesigners(_garmentTokenId).call{value : winningBid}(""); require(designerTransferSuccess, "DigitalaxAuction.resultAuction: Failed to send the designer their royalties"); } // Transfer the token to the winner garmentNft.safeTransferFrom(garmentNft.ownerOf(_garmentTokenId), winner, _garmentTokenId); emit AuctionResulted(_garmentTokenId, winner, winningBid); } /** @notice Cancels and inflight and un-resulted auctions, returning the funds to the top bidder if found @dev Only admin @param _garmentTokenId Token ID of the garment being auctioned */ function cancelAuction(uint256 _garmentTokenId) external nonReentrant { // Admin only resulting function require( accessControls.hasAdminRole(_msgSender()) || accessControls.hasSmartContractRole(_msgSender()), "DigitalaxAuction.cancelAuction: Sender must be admin or smart contract" ); // Check valid and not resulted Auction storage auction = auctions[_garmentTokenId]; // Check auction is real require(auction.endTime > 0, "DigitalaxAuction.cancelAuction: Auction does not exist"); // Check auction not already resulted require(!auction.resulted, "DigitalaxAuction.cancelAuction: auction already resulted"); // refund existing top bidder if found HighestBid storage highestBid = highestBids[_garmentTokenId]; if (highestBid.bidder != address(0)) { _refundHighestBidder(highestBid.bidder, highestBid.bid); // Clear up highest bid delete highestBids[_garmentTokenId]; } // Remove auction and top bidder delete auctions[_garmentTokenId]; emit AuctionCancelled(_garmentTokenId); } /** @notice Toggling the pause flag @dev Only admin */ function toggleIsPaused() external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.toggleIsPaused: Sender must be admin"); isPaused = !isPaused; emit PauseToggled(isPaused); } /** @notice Update the amount by which bids have to increase, across all auctions @dev Only admin @param _minBidIncrement New bid step in WEI */ function updateMinBidIncrement(uint256 _minBidIncrement) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.updateMinBidIncrement: Sender must be admin"); minBidIncrement = _minBidIncrement; emit UpdateMinBidIncrement(_minBidIncrement); } /** @notice Update the global bid withdrawal lockout time @dev Only admin @param _bidWithdrawalLockTime New bid withdrawal lock time */ function updateBidWithdrawalLockTime(uint256 _bidWithdrawalLockTime) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.updateBidWithdrawalLockTime: Sender must be admin"); bidWithdrawalLockTime = _bidWithdrawalLockTime; emit UpdateBidWithdrawalLockTime(_bidWithdrawalLockTime); } /** @notice Update the current reserve price for an auction @dev Only admin @dev Auction must exist @param _garmentTokenId Token ID of the garment being auctioned @param _reservePrice New Ether reserve price (WEI value) */ function updateAuctionReservePrice(uint256 _garmentTokenId, uint256 _reservePrice) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.updateAuctionReservePrice: Sender must be admin" ); require( auctions[_garmentTokenId].endTime > 0, "DigitalaxAuction.updateAuctionReservePrice: No Auction exists" ); auctions[_garmentTokenId].reservePrice = _reservePrice; emit UpdateAuctionReservePrice(_garmentTokenId, _reservePrice); } /** @notice Update the current start time for an auction @dev Only admin @dev Auction must exist @param _garmentTokenId Token ID of the garment being auctioned @param _startTime New start time (unix epoch in seconds) */ function updateAuctionStartTime(uint256 _garmentTokenId, uint256 _startTime) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.updateAuctionStartTime: Sender must be admin" ); require( auctions[_garmentTokenId].endTime > 0, "DigitalaxAuction.updateAuctionStartTime: No Auction exists" ); auctions[_garmentTokenId].startTime = _startTime; emit UpdateAuctionStartTime(_garmentTokenId, _startTime); } /** @notice Update the current end time for an auction @dev Only admin @dev Auction must exist @param _garmentTokenId Token ID of the garment being auctioned @param _endTimestamp New end time (unix epoch in seconds) */ function updateAuctionEndTime(uint256 _garmentTokenId, uint256 _endTimestamp) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.updateAuctionEndTime: Sender must be admin" ); require( auctions[_garmentTokenId].endTime > 0, "DigitalaxAuction.updateAuctionEndTime: No Auction exists" ); require( auctions[_garmentTokenId].startTime < _endTimestamp, "DigitalaxAuction.updateAuctionEndTime: End time must be greater than start" ); require( _endTimestamp > _getNow(), "DigitalaxAuction.updateAuctionEndTime: End time passed. Nobody can bid" ); auctions[_garmentTokenId].endTime = _endTimestamp; emit UpdateAuctionEndTime(_garmentTokenId, _endTimestamp); } /** @notice Method for updating the access controls contract used by the NFT @dev Only admin @param _accessControls Address of the new access controls contract (Cannot be zero address) */ function updateAccessControls(DigitalaxAccessControls _accessControls) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.updateAccessControls: Sender must be admin" ); require(address(_accessControls) != address(0), "DigitalaxAuction.updateAccessControls: Zero Address"); accessControls = _accessControls; emit UpdateAccessControls(address(_accessControls)); } /** @notice Method for updating platform fee @dev Only admin @param _platformFee uint256 the platform fee to set */ function updatePlatformFee(uint256 _platformFee) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.updatePlatformFee: Sender must be admin" ); platformFee = _platformFee; emit UpdatePlatformFee(_platformFee); } /** @notice Method for updating platform fee address @dev Only admin @param _platformFeeRecipient payable address the address to sends the funds to */ function updatePlatformFeeRecipient(address payable _platformFeeRecipient) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.updatePlatformFeeRecipient: Sender must be admin" ); require(_platformFeeRecipient != address(0), "DigitalaxAuction.updatePlatformFeeRecipient: Zero address"); platformFeeRecipient = _platformFeeRecipient; emit UpdatePlatformFeeRecipient(_platformFeeRecipient); } /////////////// // Accessors // /////////////// /** @notice Method for getting all info about the auction @param _garmentTokenId Token ID of the garment being auctioned */ function getAuction(uint256 _garmentTokenId) external view returns (uint256 _reservePrice, uint256 _startTime, uint256 _endTime, bool _resulted) { Auction storage auction = auctions[_garmentTokenId]; return ( auction.reservePrice, auction.startTime, auction.endTime, auction.resulted ); } /** @notice Method for getting all info about the highest bidder @param _garmentTokenId Token ID of the garment being auctioned */ function getHighestBidder(uint256 _garmentTokenId) external view returns ( address payable _bidder, uint256 _bid, uint256 _lastBidTime ) { HighestBid storage highestBid = highestBids[_garmentTokenId]; return ( highestBid.bidder, highestBid.bid, highestBid.lastBidTime ); } ///////////////////////// // Internal and Private / ///////////////////////// function _getNow() internal virtual view returns (uint256) { return block.timestamp; } /** @notice Private method doing the heavy lifting of creating an auction @param _garmentTokenId Token ID of the garment being auctioned @param _reservePrice Garment cannot be sold for less than this or minBidIncrement, whichever is higher @param _startTimestamp Unix epoch in seconds for the auction start time @param _endTimestamp Unix epoch in seconds for the auction end time. */ function _createAuction( uint256 _garmentTokenId, uint256 _reservePrice, uint256 _startTimestamp, uint256 _endTimestamp ) private { // Ensure a token cannot be re-listed if previously successfully sold require(auctions[_garmentTokenId].endTime == 0, "DigitalaxAuction.createAuction: Cannot relist"); // Check end time not before start time and that end is in the future require(_endTimestamp > _startTimestamp, "DigitalaxAuction.createAuction: End time must be greater than start"); require(_endTimestamp > _getNow(), "DigitalaxAuction.createAuction: End time passed. Nobody can bid."); // Setup the auction auctions[_garmentTokenId] = Auction({ reservePrice : _reservePrice, startTime : _startTimestamp, endTime : _endTimestamp, resulted : false }); emit AuctionCreated(_garmentTokenId); } /** @notice Used for sending back escrowed funds from a previous bid @param _currentHighestBidder Address of the last highest bidder @param _currentHighestBid Ether amount in WEI that the bidder sent when placing their bid */ function _refundHighestBidder(address payable _currentHighestBidder, uint256 _currentHighestBid) private { // refund previous best (if bid exists) (bool successRefund,) = _currentHighestBidder.call{value : _currentHighestBid}(""); require(successRefund, "DigitalaxAuction._refundHighestBidder: failed to refund previous bidder"); emit BidRefunded(_currentHighestBidder, _currentHighestBid); } }
/ Ensure a token cannot be re-listed if previously successfully sold Check end time not before start time and that end is in the future Setup the auction
function _createAuction( uint256 _garmentTokenId, uint256 _reservePrice, uint256 _startTimestamp, uint256 _endTimestamp ) private { require(auctions[_garmentTokenId].endTime == 0, "DigitalaxAuction.createAuction: Cannot relist"); require(_endTimestamp > _startTimestamp, "DigitalaxAuction.createAuction: End time must be greater than start"); require(_endTimestamp > _getNow(), "DigitalaxAuction.createAuction: End time passed. Nobody can bid."); auctions[_garmentTokenId] = Auction({ reservePrice : _reservePrice, startTime : _startTimestamp, endTime : _endTimestamp, resulted : false }); emit AuctionCreated(_garmentTokenId); } @param _currentHighestBidder Address of the last highest bidder @param _currentHighestBid Ether amount in WEI that the bidder sent when placing their bid
7,218,380
pragma solidity ^0.4.16; contract SafeMath { function safeAdd(uint256 x, uint256 y) view internal returns (uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) view internal returns (uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) view internal returns (uint256) { uint256 z = x * y; assert((x == 0) || (z / x == y)); return z; } function safeDiv(uint256 a, uint256 b) view internal returns (uint256) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } } contract Owner { // Адреса владельцев mapping ( address => bool ) public ownerAddressMap; // Соответсвие адреса владельца и его номера mapping ( address => uint256 ) public ownerAddressNumberMap; // список менеджеров mapping ( uint256 => address ) public ownerListMap; // сколько всего менеджеров uint256 public ownerCountInt = 0; // событие "изменение в контракте" event ContractManagementUpdate( string _type, address _initiator, address _to, bool _newvalue ); // модификатор - если смотрит владелец modifier isOwner { require( ownerAddressMap[msg.sender]==true ); _; } // создание/включение владельца function ownerOn( address _onOwnerAddress ) external isOwner returns (bool retrnVal) { // Check if it's a non-zero address require( _onOwnerAddress != address(0) ); // если такой владелец есть (стартового владельца удалить нельзя) if ( ownerAddressNumberMap[ _onOwnerAddress ]>0 ) { // если такой владелец отключен, влючим его обратно if ( !ownerAddressMap[ _onOwnerAddress ] ) { ownerAddressMap[ _onOwnerAddress ] = true; ContractManagementUpdate( "Owner", msg.sender, _onOwnerAddress, true ); retrnVal = true; } else { retrnVal = false; } } // если такого владеьца нет else { ownerAddressMap[ _onOwnerAddress ] = true; ownerAddressNumberMap[ _onOwnerAddress ] = ownerCountInt; ownerListMap[ ownerCountInt ] = _onOwnerAddress; ownerCountInt++; ContractManagementUpdate( "Owner", msg.sender, _onOwnerAddress, true ); retrnVal = true; } } // отключение менеджера function ownerOff( address _offOwnerAddress ) external isOwner returns (bool retrnVal) { // если такой менеджер есть и он не 0-вой, а также активен // 0-вой менеджер не может быть отключен if ( ownerAddressNumberMap[ _offOwnerAddress ]>0 && ownerAddressMap[ _offOwnerAddress ] ) { ownerAddressMap[ _offOwnerAddress ] = false; ContractManagementUpdate( "Owner", msg.sender, _offOwnerAddress, false ); retrnVal = true; } else { retrnVal = false; } } // конструктор, при создании контракта добалвяет создателя в "неудаляемые" создатели function Owner() public { // создаем владельца ownerAddressMap[ msg.sender ] = true; ownerAddressNumberMap[ msg.sender ] = ownerCountInt; ownerListMap[ ownerCountInt ] = msg.sender; ownerCountInt++; } } contract SpecialManager is Owner { // адреса специальных менеджеров mapping ( address => bool ) public specialManagerAddressMap; // Соответсвие адреса специального менеджера и его номера mapping ( address => uint256 ) public specialManagerAddressNumberMap; // список специальноых менеджеров mapping ( uint256 => address ) public specialManagerListMap; // сколько всего специальных менеджеров uint256 public specialManagerCountInt = 0; // модификатор - если смотрит владелец или специальный менеджер modifier isSpecialManagerOrOwner { require( specialManagerAddressMap[msg.sender]==true || ownerAddressMap[msg.sender]==true ); _; } // создание/включение специального менеджера function specialManagerOn( address _onSpecialManagerAddress ) external isOwner returns (bool retrnVal) { // Check if it's a non-zero address require( _onSpecialManagerAddress != address(0) ); // если такой менеджер есть if ( specialManagerAddressNumberMap[ _onSpecialManagerAddress ]>0 ) { // если такой менеджер отключен, влючим его обратно if ( !specialManagerAddressMap[ _onSpecialManagerAddress ] ) { specialManagerAddressMap[ _onSpecialManagerAddress ] = true; ContractManagementUpdate( "Special Manager", msg.sender, _onSpecialManagerAddress, true ); retrnVal = true; } else { retrnVal = false; } } // если такого менеджера нет else { specialManagerAddressMap[ _onSpecialManagerAddress ] = true; specialManagerAddressNumberMap[ _onSpecialManagerAddress ] = specialManagerCountInt; specialManagerListMap[ specialManagerCountInt ] = _onSpecialManagerAddress; specialManagerCountInt++; ContractManagementUpdate( "Special Manager", msg.sender, _onSpecialManagerAddress, true ); retrnVal = true; } } // отключение менеджера function specialManagerOff( address _offSpecialManagerAddress ) external isOwner returns (bool retrnVal) { // если такой менеджер есть и он не 0-вой, а также активен // 0-вой менеджер не может быть отключен if ( specialManagerAddressNumberMap[ _offSpecialManagerAddress ]>0 && specialManagerAddressMap[ _offSpecialManagerAddress ] ) { specialManagerAddressMap[ _offSpecialManagerAddress ] = false; ContractManagementUpdate( "Special Manager", msg.sender, _offSpecialManagerAddress, false ); retrnVal = true; } else { retrnVal = false; } } // конструктор, добавляет создателя в суперменеджеры function SpecialManager() public { // создаем менеджера specialManagerAddressMap[ msg.sender ] = true; specialManagerAddressNumberMap[ msg.sender ] = specialManagerCountInt; specialManagerListMap[ specialManagerCountInt ] = msg.sender; specialManagerCountInt++; } } contract Manager is SpecialManager { // адрес менеджеров mapping ( address => bool ) public managerAddressMap; // Соответсвие адреса менеджеров и его номера mapping ( address => uint256 ) public managerAddressNumberMap; // список менеджеров mapping ( uint256 => address ) public managerListMap; // сколько всего менеджеров uint256 public managerCountInt = 0; // модификатор - если смотрит владелец или менеджер modifier isManagerOrOwner { require( managerAddressMap[msg.sender]==true || ownerAddressMap[msg.sender]==true ); _; } // создание/включение менеджера function managerOn( address _onManagerAddress ) external isOwner returns (bool retrnVal) { // Check if it's a non-zero address require( _onManagerAddress != address(0) ); // если такой менеджер есть if ( managerAddressNumberMap[ _onManagerAddress ]>0 ) { // если такой менеджер отключен, влючим его обратно if ( !managerAddressMap[ _onManagerAddress ] ) { managerAddressMap[ _onManagerAddress ] = true; ContractManagementUpdate( "Manager", msg.sender, _onManagerAddress, true ); retrnVal = true; } else { retrnVal = false; } } // если такого менеджера нет else { managerAddressMap[ _onManagerAddress ] = true; managerAddressNumberMap[ _onManagerAddress ] = managerCountInt; managerListMap[ managerCountInt ] = _onManagerAddress; managerCountInt++; ContractManagementUpdate( "Manager", msg.sender, _onManagerAddress, true ); retrnVal = true; } } // отключение менеджера function managerOff( address _offManagerAddress ) external isOwner returns (bool retrnVal) { // если такой менеджер есть и он не 0-вой, а также активен // 0-вой менеджер не может быть отключен if ( managerAddressNumberMap[ _offManagerAddress ]>0 && managerAddressMap[ _offManagerAddress ] ) { managerAddressMap[ _offManagerAddress ] = false; ContractManagementUpdate( "Manager", msg.sender, _offManagerAddress, false ); retrnVal = true; } else { retrnVal = false; } } // конструктор, добавляет создателя в менеджеры function Manager() public { // создаем менеджера managerAddressMap[ msg.sender ] = true; managerAddressNumberMap[ msg.sender ] = managerCountInt; managerListMap[ managerCountInt ] = msg.sender; managerCountInt++; } } contract Management is Manager { // текстовое описание контракта string public description = ""; // текущий статус разрешения транзакций // TRUE - транзакции возможны // FALSE - транзакции не возможны bool public transactionsOn = false; // текущий статус эмиссии // TRUE - эмиссия возможна, менеджеры могут добавлять в контракт токены // FALSE - эмиссия невозможна, менеджеры не могут добавлять в контракт токены bool public emissionOn = true; // потолок эмиссии uint256 public tokenCreationCap = 0; // модификатор - транзакции возможны modifier isTransactionsOn{ require( transactionsOn ); _; } // модификатор - эмиссия возможна modifier isEmissionOn{ require( emissionOn ); _; } // функция изменения статуса транзакций function transactionsStatusUpdate( bool _on ) external isOwner { transactionsOn = _on; } // функция изменения статуса эмиссии function emissionStatusUpdate( bool _on ) external isOwner { emissionOn = _on; } // установка потолка эмиссии function tokenCreationCapUpdate( uint256 _newVal ) external isOwner { tokenCreationCap = _newVal; } // событие, "смена описания" event DescriptionPublished( string _description, address _initiator); // изменение текста function descriptionUpdate( string _newVal ) external isOwner { description = _newVal; DescriptionPublished( _newVal, msg.sender ); } } // Токен-контракт FoodCoin Ecosystem contract FoodcoinEcosystem is SafeMath, Management { // название токена string public constant name = "FoodCoin EcoSystem"; // короткое название токена string public constant symbol = "FOOD"; // точность токена (знаков после запятой для вывода в кошельках) uint256 public constant decimals = 8; // общее кол-во выпущенных токенов uint256 public totalSupply = 0; // состояние счета mapping ( address => uint256 ) balances; // список всех счетов mapping ( uint256 => address ) public balancesListAddressMap; // соответсвие счета и его номера mapping ( address => uint256 ) public balancesListNumberMap; // текстовое описание счета mapping ( address => string ) public balancesAddressDescription; // общее кол-во всех счетов uint256 balancesCountInt = 1; // делегирование на управление счетом на определенную сумму mapping ( address => mapping ( address => uint256 ) ) allowed; // событие - транзакция event Transfer(address _from, address _to, uint256 _value, address _initiator); // событие делегирование управления счетом event Approval(address indexed _owner, address indexed _spender, uint256 _value); // событие - эмиссия event TokenEmissionEvent( address initiatorAddress, uint256 amount, bool emissionOk ); // событие - списание средств event WithdrawEvent( address initiatorAddress, address toAddress, bool withdrawOk, uint256 withdrawValue, uint256 newBalancesValue ); // проссмотра баланса счета function balanceOf( address _owner ) external view returns ( uint256 ) { return balances[ _owner ]; } // Check if a given user has been delegated rights to perform transfers on behalf of the account owner function allowance( address _owner, address _initiator ) external view returns ( uint256 remaining ) { return allowed[ _owner ][ _initiator ]; } // общее кол-во счетов function balancesQuantity() external view returns ( uint256 ) { return balancesCountInt - 1; } // функция непосредственного перевода токенов. Если это первое получение средств для какого-то счета, то также создается детальная информация по этому счету function _addClientAddress( address _balancesAddress, uint256 _amount ) internal { // check if this address is not on the list yet if ( balancesListNumberMap[ _balancesAddress ] == 0 ) { // add it to the list balancesListAddressMap[ balancesCountInt ] = _balancesAddress; balancesListNumberMap[ _balancesAddress ] = balancesCountInt; // increment account counter balancesCountInt++; } // add tokens to the account balances[ _balancesAddress ] = safeAdd( balances[ _balancesAddress ], _amount ); } // Internal function that performs the actual transfer (cannot be called externally) function _transfer( address _from, address _to, uint256 _value ) internal isTransactionsOn returns ( bool success ) { // If the amount to transfer is greater than 0, and sender has funds available if ( _value > 0 && balances[ _from ] >= _value ) { // Subtract from sender account balances[ _from ] -= _value; // Add to receiver's account _addClientAddress( _to, _value ); // Perform the transfer Transfer( _from, _to, _value, msg.sender ); // Successfully completed transfer return true; } // Return false if there are problems else { return false; } } // функция перевода токенов function transfer(address _to, uint256 _value) external isTransactionsOn returns ( bool success ) { return _transfer( msg.sender, _to, _value ); } // функция перевода токенов с делегированного счета function transferFrom(address _from, address _to, uint256 _value) external isTransactionsOn returns ( bool success ) { // Check if the transfer initiator has permissions to move funds from the sender's account if ( allowed[_from][msg.sender] >= _value ) { // If yes - perform transfer if ( _transfer( _from, _to, _value ) ) { // Decrease the total amount that initiator has permissions to access allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender], _value); return true; } else { return false; } } else { return false; } } // функция делегирования управления счетом на определенную сумму function approve( address _initiator, uint256 _value ) external isTransactionsOn returns ( bool success ) { // Grant the rights for a certain amount of tokens only allowed[ msg.sender ][ _initiator ] = _value; // Initiate the Approval event Approval( msg.sender, _initiator, _value ); return true; } // функция эмиссии (менеджер или владелец контракта создает токены и отправляет их на определенный счет) function tokenEmission(address _reciever, uint256 _amount) external isManagerOrOwner isEmissionOn returns ( bool returnVal ) { // Check if it's a non-zero address require( _reciever != address(0) ); // Calculate number of tokens after generation uint256 checkedSupply = safeAdd( totalSupply, _amount ); // сумма к эмиссии uint256 amountTmp = _amount; // Если потолок эмиссии установлен, то нельзя выпускать больше этого потолка if ( tokenCreationCap > 0 && tokenCreationCap < checkedSupply ) { amountTmp = 0; } // если попытка добавить больше 0-ля токенов if ( amountTmp > 0 ) { // If no error, add generated tokens to a given address _addClientAddress( _reciever, amountTmp ); // increase total supply of tokens totalSupply = checkedSupply; TokenEmissionEvent( msg.sender, _amount, true); } else { returnVal = false; TokenEmissionEvent( msg.sender, _amount, false); } } // функция списания токенов function withdraw( address _to, uint256 _amount ) external isSpecialManagerOrOwner returns ( bool returnVal, uint256 withdrawValue, uint256 newBalancesValue ) { // check if this is a valid account if ( balances[ _to ] > 0 ) { // сумма к списанию uint256 amountTmp = _amount; // нельзя списать больше, чем есть на счету if ( balances[ _to ] < _amount ) { amountTmp = balances[ _to ]; } // проводим списывание balances[ _to ] = safeSubtract( balances[ _to ], amountTmp ); // меняем текущее общее кол-во токенов totalSupply = safeSubtract( totalSupply, amountTmp ); // возвращаем ответ returnVal = true; withdrawValue = amountTmp; newBalancesValue = balances[ _to ]; WithdrawEvent( msg.sender, _to, true, amountTmp, balances[ _to ] ); } else { returnVal = false; withdrawValue = 0; newBalancesValue = 0; WithdrawEvent( msg.sender, _to, false, _amount, balances[ _to ] ); } } // добавление описания к счету function balancesAddressDescriptionUpdate( string _newDescription ) external returns ( bool returnVal ) { // если такой аккаунт есть или владелец контракта if ( balancesListNumberMap[ msg.sender ] > 0 || ownerAddressMap[msg.sender]==true ) { balancesAddressDescription[ msg.sender ] = _newDescription; returnVal = true; } else { returnVal = false; } } }
общее кол-во счетов
function balancesQuantity() external view returns ( uint256 ) { return balancesCountInt - 1; }
2,573,493
pragma solidity 0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Helps contracts guard agains reentrancy attacks. * @author Remco Bloemen <remco@2π.com> * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancy_lock); reentrancy_lock = true; _; reentrancy_lock = false; } } /** * @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; } } /** * EtherButton * * A game of financial hot potato. Players pay to click EtherButton. * Each player is given 105% of their payment by each subsequent player. * A seven hour timer resets after every click. The round advances once the timer reaches zero. * * Bonus: * For every player payout, an additional 1% is stored as an end-of-round bonus. * Each player is entitled to their bonus if they click EtherButton during the *next* round. * 0.500 ETH is given to the last player of every round and their bonus is unlocked immediately. * Unclaimed bonuses are rolled into future rounds. **/ contract EtherButton is Ownable, ReentrancyGuard { // Use basic math operators which have integer overflow protection built into them. // Simplifies code greatly by reducing the need to constantly check inputs for overflow. using SafeMath for uint; // Best practices say to prefix events with Log to avoid confusion. // https://consensys.github.io/smart-contract-best-practices/recommendations/#differentiate-functions-and-events event LogClick( uint _id, uint _price, uint _previousPrice, uint _endTime, uint _clickCount, uint _totalBonus, address _activePlayer, uint _activePlayerClickCount, uint _previousRoundTotalBonus ); event LogClaimBonus(address _recipient, uint _bonus); event LogPlayerPayout(address _recipient, uint _amount); event LogSendPaymentFailure(address _recipient, uint _amount); // Represent fractions as numerator/denominator because Solidity doesn't support decimals. // It's okay to use ".5 ether" because it converts to "500000000000000000 wei" uint public constant INITIAL_PRICE = .5 ether; uint public constant ROUND_DURATION = 7 hours; // 5% price increase is allocated to the player. uint private constant PLAYER_PROFIT_NUMERATOR = 5; uint private constant PLAYER_PROFIT_DENOMINATOR = 100; // 1% price increase is allocated to player bonuses. uint private constant BONUS_NUMERATOR = 1; uint private constant BONUS_DENOMINATOR = 100; // 2.5% price increase is allocated to the owner. uint private constant OWNER_FEE_NUMERATOR = 25; uint private constant OWNER_FEE_DENOMINATOR = 1000; // EtherButton is comprised of many rounds. Each round contains // an isolated instance of game state. struct Round { uint id; uint price; uint previousPrice; uint endTime; uint clickCount; uint totalBonus; uint claimedBonus; address activePlayer; mapping (address => uint) playerClickCounts; mapping (address => bool) bonusClaimedList; } // A list of all the rounds which have been played as well as // the id of the current (active) round. mapping (uint => Round) public Rounds; uint public RoundId; /** * Create the contract with an initial 'Round 0'. This round has already expired which will cause the first * player interaction to start Round 1. This is simpler than introducing athe concept of a 'paused' round. **/ function EtherButton() public { initializeRound(); Rounds[RoundId].endTime = now.sub(1); } /** * Performs a single 'click' of EtherButton. * * Advances the round if the previous round's endTime has passed. This needs to be done * just-in-time because code isn't able to execute on a timer - it needs funding. * * Refunds the player any extra money they may have sent. Pays the last player and the owner. * Marks the player as the active player so that they're next to be paid. * * Emits an event showing the current state of EtherButton and returns the state, too. **/ function click() nonReentrant external payable { // Owner is not allowed to play. require(msg.sender != owner); // There's no way to advance the round exactly at a specific time because the contract only runs // when value is sent to it. So, round advancement must be done just-in-time whenever a player pays to click. // Only advance the round when a player clicks because the next round's timer will begin immediately. if (getIsRoundOver(RoundId)) { advanceRound(); } Round storage round = Rounds[RoundId]; // Safe-guard against spam clicks from a single player. require(msg.sender != round.activePlayer); // Safe-guard against underpayment. require(msg.value >= round.price); // Refund player extra value beyond price. If EtherButton is very popular then its price may // attempt to increase multiple times in a single block. In this situation, the first attempt // would be successful, but subsequent attempts would fail due to insufficient funding. // To combat this issue, a player may send more value than necessary to // increase the chance of the price being payable with the amount of value they sent. if (msg.value > round.price) { sendPayment(msg.sender, msg.value.sub(round.price)); } // Pay the active player and owner for each click past the first. if (round.activePlayer != address(0)) { // Pay the player first because that seems respectful. // Log the player payouts to show on the website. uint playerPayout = getPlayerPayout(round.previousPrice); sendPayment(round.activePlayer, playerPayout); LogPlayerPayout(round.activePlayer, playerPayout); // Pay the contract owner as fee for game creation. Thank you! <3 sendPayment(owner, getOwnerFee(round.previousPrice)); // Keep track of bonuses collected at same time as sending payouts to ensure financial consistency. round.totalBonus = round.totalBonus.add(getBonusFee(round.previousPrice)); } // Update round state to reflect the additional click round.activePlayer = msg.sender; round.playerClickCounts[msg.sender] = round.playerClickCounts[msg.sender].add(1); round.clickCount = round.clickCount.add(1); round.previousPrice = round.price; // Increment the price by 8.50% round.price = getNextPrice(round.price); // Reset the round timer round.endTime = now.add(ROUND_DURATION); // Log an event with relevant information from the round's state. LogClick( round.id, round.price, round.previousPrice, round.endTime, round.clickCount, round.totalBonus, msg.sender, round.playerClickCounts[msg.sender], Rounds[RoundId.sub(1)].totalBonus ); } /** * Provides bonus payments to players who wish to claim them. * Bonuses accrue over the course of a round for those playing in the round. * Bonuses may be claimed once the next round starts, but will remain locked until * players participate in that round. The last active player of the previous round * has their bonus unlocked immediately without need to play in the next round. **/ function claimBonus() nonReentrant external { // NOTE: The only way to advance the round is to run the 'click' method. When a round is over, it will have expired, // but RoundId will not have (yet) incremented. So, claimBonus needs to check the previous round. This allows EtherButton // to never enter a 'paused' state, which is less code (aka more reliable) but it does have some edge cases. uint roundId = getIsRoundOver(RoundId) ? RoundId.add(1) : RoundId; uint previousRoundId = roundId.sub(1); bool isBonusClaimed = getIsBonusClaimed(previousRoundId, msg.sender); // If player has already claimed their bonus exit early to keep code simple and cheap to run. if (isBonusClaimed) { return; } // If a player can't claim their bonus because they haven't played during the current round // and they were not the last player in the previous round then exit as they're not authorized. bool isBonusUnlockExempt = getIsBonusUnlockExempt(previousRoundId, msg.sender); bool isBonusUnlocked = getPlayerClickCount(roundId, msg.sender) > 0; if (!isBonusUnlockExempt && !isBonusUnlocked) { return; } // If player is owed money from participation in previous round - send it. Round storage previousRound = Rounds[previousRoundId]; uint playerClickCount = previousRound.playerClickCounts[msg.sender]; uint roundClickCount = previousRound.clickCount; // NOTE: Be sure to multiply first to avoid decimal precision math. uint bonus = previousRound.totalBonus.mul(playerClickCount).div(roundClickCount); // If the current player is owed a refund from previous round fulfill that now. // This is better than forcing the player to make a separate requests for // bonuses and refund payouts. if (previousRound.activePlayer == msg.sender) { bonus = bonus.add(INITIAL_PRICE); } previousRound.bonusClaimedList[msg.sender] = true; previousRound.claimedBonus = previousRound.claimedBonus.add(bonus); sendPayment(msg.sender, bonus); // Let the EtherButton website know a bonus was claimed successfully so it may update. LogClaimBonus(msg.sender, bonus); } /** * Returns true once the given player has claimed their bonus for the given round. * Bonuses are only able to be claimed once per round per player. **/ function getIsBonusClaimed(uint roundId, address player) public view returns (bool) { return Rounds[roundId].bonusClaimedList[player]; } /** * Returns the number of times the given player has clicked EtherButton during the given round. **/ function getPlayerClickCount(uint roundId, address player) public view returns (uint) { return Rounds[roundId].playerClickCounts[player]; } /** * Returns true if the given player does not need to be unlocked to claim their bonus. * This is true when they were the last player to click EtherButton in the previous round. * That player deserves freebies for losing. So, they get their bonus unlocked early. **/ function getIsBonusUnlockExempt(uint roundId, address player) public view returns (bool) { return Rounds[roundId].activePlayer == player; } /** * Returns true if enough time has elapsed since the active player clicked the * button to consider the given round complete. **/ function getIsRoundOver(uint roundId) private view returns (bool) { return now > Rounds[roundId].endTime; } /** * Signal the completion of a round and the start of the next by moving RoundId forward one. * As clean-up before the round change occurs, join all unclaimed player bonuses together and move them * forward one round. Just-in-time initialize the next round's state once RoundId is pointing to it because * an unknown number of rounds may be played. So, it's impossible to initialize all rounds at contract creation. **/ function advanceRound() private { if (RoundId > 1) { // Take all of the previous rounds unclaimed bonuses and roll them forward. Round storage previousRound = Rounds[RoundId.sub(1)]; // If the active player of the previous round didn't claim their refund then they lose the ability to claim it. // Their refund is also rolled into the bonuses for the next round. uint remainingBonus = previousRound.totalBonus.add(INITIAL_PRICE).sub(previousRound.claimedBonus); Rounds[RoundId].totalBonus = Rounds[RoundId].totalBonus.add(remainingBonus); } RoundId = RoundId.add(1); initializeRound(); } /** * Sets the current round's default values. Initialize the price to 0.500 ETH, * the endTime to 7 hours past the current time and sets the round id. The round is * also started as the endTime is now ticking down. **/ function initializeRound() private { Rounds[RoundId].id = RoundId; Rounds[RoundId].endTime = block.timestamp.add(ROUND_DURATION); Rounds[RoundId].price = INITIAL_PRICE; } /** * Sends an amount of Ether to the recipient. Returns true if it was successful. * Logs payment failures to provide documentation on attacks against the contract. **/ function sendPayment(address recipient, uint amount) private returns (bool) { assert(recipient != address(0)); assert(amount > 0); // It's considered good practice to require users to pull payments rather than pushing // payments to them. Since EtherButton pays the previous player immediately, it has to mitigate // a denial-of-service attack. A malicious contract might always reject money which is sent to it. // This contract could be used to disrupt EtherButton if an assumption is made that money will // always be sent successfully. // https://github.com/ConsenSys/smart-contract-best-practices/blob/master/docs/recommendations.md#favor-pull-over-push-for-external-calls // Intentionally not using recipient.transfer to prevent this DOS attack vector. bool result = recipient.send(amount); // NOTE: Initially, this was written to allow users to reclaim funds on failure. // This was removed due to concerns of allowing attackers to retrieve their funds. It is // not possible for a regular wallet to reject a payment. if (!result) { // Log the failure so attempts to compromise the contract are documented. LogSendPaymentFailure(recipient, amount); } return result; } /** Returns the next price to click EtherButton. The returned value should be 8.50% larger than the current price: - 5.00% is paid to the player. - 1.00% is paid as bonuses. - 2.50% is paid to the owner. **/ function getNextPrice(uint price) private pure returns (uint) { uint playerFee = getPlayerFee(price); assert(playerFee > 0); uint bonusFee = getBonusFee(price); assert(bonusFee > 0); uint ownerFee = getOwnerFee(price); assert(ownerFee > 0); return price.add(playerFee).add(bonusFee).add(ownerFee); } /** * Returns 1.00% of the given price. Be sure to multiply before dividing to avoid decimals. **/ function getBonusFee(uint price) private pure returns (uint) { return price.mul(BONUS_NUMERATOR).div(BONUS_DENOMINATOR); } /** * Returns 2.50% of the given price. Be sure to multiply before dividing to avoid decimals. **/ function getOwnerFee(uint price) private pure returns (uint) { return price.mul(OWNER_FEE_NUMERATOR).div(OWNER_FEE_DENOMINATOR); } /** * Returns 5.00% of the given price. Be sure to multiply before dividing to avoid decimals. **/ function getPlayerFee(uint price) private pure returns (uint) { return price.mul(PLAYER_PROFIT_NUMERATOR).div(PLAYER_PROFIT_DENOMINATOR); } /** * Returns the total amount of Ether the active player will receive. This is * 105.00% of their initial price paid. **/ function getPlayerPayout(uint price) private pure returns (uint) { return price.add(getPlayerFee(price)); } }
Sends an amount of Ether to the recipient. Returns true if it was successful. Logs payment failures to provide documentation on attacks against the contract./ It's considered good practice to require users to pull payments rather than pushing payments to them. Since EtherButton pays the previous player immediately, it has to mitigate a denial-of-service attack. A malicious contract might always reject money which is sent to it. This contract could be used to disrupt EtherButton if an assumption is made that money will always be sent successfully. https:github.com/ConsenSys/smart-contract-best-practices/blob/master/docs/recommendations.mdfavor-pull-over-push-for-external-calls Intentionally not using recipient.transfer to prevent this DOS attack vector. NOTE: Initially, this was written to allow users to reclaim funds on failure. This was removed due to concerns of allowing attackers to retrieve their funds. It is not possible for a regular wallet to reject a payment. Log the failure so attempts to compromise the contract are documented.
function sendPayment(address recipient, uint amount) private returns (bool) { assert(recipient != address(0)); assert(amount > 0); bool result = recipient.send(amount); if (!result) { LogSendPaymentFailure(recipient, amount); } return result; } 8.50% larger than the current price: - 5.00% is paid to the player. - 1.00% is paid as bonuses. - 2.50% is paid to the owner.
1,306,712
./partial_match/1/0xffbaC21a641Dcfe4552920138D90F3638B3c9fba/sources/Governance.sol
Time delay between proposal vote completion and its execution Time before a passed proposal is considered expired The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed The number of votes required in order for a voter to become a proposer The delay before voting on a proposal may take place, once proposed It is needed to prevent reorg attacks that replace the proposal The duration of voting on a proposal If the outcome of a proposal changes during CLOSING_PERIOD, the vote will be extended by VOTE_EXTEND_TIME (no more than once) If the outcome of a proposal changes during CLOSING_PERIOD, the vote will be extended by VOTE_EXTEND_TIME (no more than once)
function _castVote( address voter, uint256 proposalId, bool support ) internal virtual; } pragma solidity ^0.6.0; modifier onlySelf { require(msg.sender == address(this), "Governance: unauthorized"); _; }
2,613,368
pragma solidity ^0.5.9; /** * Math operations with safety checks */ library SafeMath { function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function safeMul(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 safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function safeMod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } contract Mero { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string memory tokenName, uint8 decimalUnits, string memory tokenSymbol ) public { balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; owner = msg.sender; } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { require(_to != address(0), "Cannot use zero address"); require(_value > 0, "Cannot use zero value"); require (balanceOf[msg.sender] >= _value, "Balance not enough"); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to], "Overflow" ); // Check for overflows uint previousBalances = balanceOf[msg.sender] + balanceOf[_to]; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place assert(balanceOf[msg.sender] + balanceOf[_to] == previousBalances); } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { require (_value > 0, "Cannot use zero"); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0), "Cannot use zero address"); require(_value > 0, "Cannot use zero value"); require( balanceOf[_from] >= _value, "Balance not enough" ); require( balanceOf[_to] + _value > balanceOf[_to], "Cannot overflow" ); require( _value <= allowance[_from][msg.sender], "Cannot over allowance" ); balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } }
Transfer tokens Send `_value` tokens to `_to` from your account _to The address of the recipient _value the amount to send/
function transfer(address _to, uint256 _value) public { require(_to != address(0), "Cannot use zero address"); require(_value > 0, "Cannot use zero value"); uint previousBalances = balanceOf[msg.sender] + balanceOf[_to]; assert(balanceOf[msg.sender] + balanceOf[_to] == previousBalances); }
12,882,723
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "../ERC721/extensions/ERC721URIContract.sol"; import "../ERC721/extensions/ERC721Pausable.sol"; import "../utils/Base64.sol"; import "./INamespaceMinter.sol"; // // ______ _______ ____ ____ _______ ____ ____ // .' ___ ||_ __ \ |_ _||_ _| |_ __ \|_ || _| // / .' \_| | |__) | \ \ / / | |__) | | |__| | // | | ____ | __ / \ \/ / | ___/ | __ | // \ `.___] |_| | \ \_ _| |_ _ _| |_ _| | | |_ // `._____.'|____| |___||______|(_)|_____| |____||____| // // CROSS CHAIN NFT MARKETPLACE // https://www.gry.ph/ // contract GryphNamespaceRegistry is INamespaceMinter, Ownable, AccessControlEnumerable, ERC721URIContract, ERC721Pausable { using Strings for uint256; // ============ Constants ============ //all custom roles bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant CURATOR_ROLE = keccak256("CURATOR_ROLE"); //royalty percent uint256 private constant _ROYALTY_PERCENT = 500; //bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; // ============ Storage ============ //mapping of token id to name mapping(uint256 => string) private _registry; //mapping of names to blacklist mapping(string => bool) public blacklisted; // ============ Deploy ============ /** * @dev Sets contract URI */ constructor(string memory uri) { address sender = _msgSender(); //set up roles for contract deployer _setupRole(DEFAULT_ADMIN_ROLE, sender); _setContractURI(uri); } // ============ Read Methods ============ /** * @dev See {IERC721Metadata-name}. */ function name() external pure returns(string memory) { return "Gryph Namespaces"; } /** * @dev implements ERC2981 `royaltyInfo()` */ function royaltyInfo(uint256, uint256 salePrice) external view returns(address receiver, uint256 royaltyAmount) { return ( payable(address(owner())), (salePrice * _ROYALTY_PERCENT) / 10000 ); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721) returns(bool) { //support ERC2981 return interfaceId == _INTERFACE_ID_ERC2981 || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() external pure returns(string memory) { return "GNS"; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view returns(string memory) { if(!_exists(tokenId)) revert InvalidCall(); string memory namespace = _registry[tokenId]; return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(bytes(abi.encodePacked( '{"name":"', namespace, '.gry.ph",', '"description": "', _description(), '",', '"image":"data:image/svg+xml;base64,', _svg64(namespace), '"}' ))) ) ); } // ============ Admin Methods ============ /** * @dev Assigns a name to a new owner. This would only ever be called * if there was a reported breach of a trademark */ function assign(uint256 tokenId, address recipient) external onlyRole(CURATOR_ROLE) { _transfer(ownerOf(tokenId), recipient, tokenId); } /** * @dev Disallows `names` to be minted */ function blacklist(string[] memory names, bool banned) external onlyRole(CURATOR_ROLE) { for (uint256 i = 0; i < names.length; i++) { blacklisted[names[i]] = banned; } } /** * @dev Allow admin to mint a name without paying (used for airdrops) */ function mint(address recipient, string memory namespace) external onlyRole(MINTER_ROLE) { _nameMint(recipient, namespace); } // ============ Private Methods ============ /** * @dev See {ERC721B-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function _description() private pure returns(string memory) { return "GRY.PH is a cross chain NFT marketplace. Holders of this collection namespace have the rights to customize the content available."; } function _grid() private pure returns(uint256[5][73] memory) { return [ [uint256(25), 25, 13, 125, 0], [uint256(50), 25, 38, 100, 0], [uint256(75), 25, 88, 75, 0], [uint256(25), 25, 163, 50, 0], [uint256(25), 25, 188, 25, 0], [uint256(25), 25, 213, 0, 0], [uint256(25), 25, 288, 75, 0], [uint256(25), 25, 263, 50, 0], [uint256(25), 25, 238, 25, 0], [uint256(25), 50, 338, 75, 0], [uint256(25), 25, 363, 125, 0], [uint256(25), 25, 388, 150, 0], [uint256(25), 25, 413, 175, 0], [uint256(25), 75, 438, 200, 0], [uint256(50), 25, 38, 150, 0], [uint256(25), 25, 113, 175, 0], [uint256(25), 75, 88, 200, 0], [uint256(25), 25, 113, 275, 0], [uint256(25), 25, 13, 325, 0], [uint256(50), 25, 38, 300, 0], [uint256(50), 25, 38, 350, 0], [uint256(75), 25, 88, 375, 0], [uint256(25), 25, 163, 400, 0], [uint256(25), 25, 188, 425, 0], [uint256(25), 25, 213, 450, 0], [uint256(25), 25, 288, 375, 0], [uint256(25), 25, 263, 400, 0], [uint256(25), 25, 238, 425, 0], [uint256(25), 50, 338, 350, 0], [uint256(25), 25, 363, 325, 0], [uint256(25), 25, 388, 300, 0], [uint256(25), 25, 413, 275, 0], [uint256(50), 25, 38, 125, 1], [uint256(50), 25, 38, 325, 1], [uint256(50), 25, 88, 150, 1], [uint256(75), 25, 88, 100, 1], [uint256(75), 25, 88, 350, 1], [uint256(50), 25, 88, 300, 1], [uint256(25), 75, 113, 200, 1], [uint256(25), 25, 163, 75, 1], [uint256(75), 25, 188, 50, 1], [uint256(25), 25, 213, 25, 1], [uint256(25), 25, 263, 75, 1], [uint256(25), 25, 138, 175, 1], [uint256(25), 25, 138, 275, 1], [uint256(75), 25, 188, 400, 1], [uint256(25), 25, 213, 425, 1], [uint256(25), 25, 263, 375, 1], [uint256(25), 25, 163, 375, 1], [uint256(25), 25, 88, 125, 2], [uint256(25), 25, 88, 325, 2], [uint256(25), 50, 213, 100, 2], [uint256(25), 50, 238, 125, 2], [uint256(25), 50, 238, 300, 2], [uint256(25), 25, 288, 175, 2], [uint256(25), 25, 288, 275, 2], [uint256(25), 50, 213, 325, 2], [uint256(25), 25, 213, 200, 2], [uint256(25), 25, 213, 250, 2], [uint256(25), 25, 363, 150, 2], [uint256(25), 25, 363, 300, 2], [uint256(25), 125, 388, 175, 2], [uint256(75), 75, 238, 200, 3], [uint256(25), 25, 263, 175, 3], [uint256(25), 25, 263, 275, 3], [uint256(25), 25, 288, 150, 3], [uint256(25), 25, 288, 300, 3], [uint256(25), 50, 313, 75, 3], [uint256(50), 50, 313, 125, 3], [uint256(75), 125, 313, 175, 3], [uint256(50), 50, 313, 300, 3], [uint256(25), 50, 313, 350, 3], [uint256(25), 75, 413, 200, 3] ]; } function _svg64(string memory namespace) private pure returns(string memory) { bytes memory svg = abi.encodePacked( '<svg width="475" height="475" xmlns="http://www.w3.org/2000/svg"><g><rect height="475" width="475" fill="#ffffff"/>' ); string[4] memory color = [ 'D0D0D0', 'F5F5F5', 'EDEDED', 'DBDBDB' ]; uint256[5][73] memory grid = _grid(); for (uint8 i = 0; i < grid.length; i++) { svg = abi.encodePacked(svg, '<rect height="', grid[i][0].toString(), '" width="', grid[i][1].toString(), '" y="', grid[i][2].toString(), '" x="', grid[i][3].toString(), '" fill="#', color[grid[i][4]],'"/>' ); } svg = abi.encodePacked(svg, '<text font-family="', "'Courier New'", '" font-weight="bold" font-size="30" y="60%" x="50%" fill="#444" dominant-baseline="middle" text-anchor="middle">gry.ph</text>', '<text id="name" font-family="', "'Courier New'", '" font-weight="bold" font-size="30" y="50%" x="50%" fill="#000" dominant-baseline="middle" text-anchor="middle">', namespace,'</text>', '</g></svg>' ); return Base64.encode(svg); } function _nameMint(address recipient, string memory namespace) private { //if blacklisted if (blacklisted[namespace]) revert InvalidCall(); //determine token id from name bytes32 nameHash = keccak256(abi.encodePacked(namespace)); if (nameHash.length < 32) revert InvalidCall(); uint256 tokenId = uint256(nameHash); //now mint _safeMint(recipient, tokenId); _registry[tokenId] = namespace; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 override returns (address) { return _roleMembers[role].at(index); } /** * @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 override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 contract with a URI descriptor */ abstract contract ERC721URIContract is ERC721 { //immutable contract uri string private _contractURI; /** * @dev The URI for contract data ex. https://creatures-api.opensea.io/contract/opensea-creatures/contract.json * Example Format: * { * "name": "OpenSea Creatures", * "description": "OpenSea Creatures are adorable aquatic beings primarily for demonstrating what can be done using the OpenSea platform. Adopt one today to try out all the OpenSea buying, selling, and bidding feature set.", * "image": "https://openseacreatures.io/image.png", * "external_link": "https://openseacreatures.io", * "seller_fee_basis_points": 100, # Indicates a 1% seller fee. * "fee_recipient": "0xA97F337c39cccE66adfeCB2BF99C1DdC54C2D721" # Where seller fees will be paid to. * } */ function contractURI() external view returns (string memory) { return _contractURI; } /** * @dev Sets contract uri */ function _setContractURI(string memory uri) internal virtual { _contractURI = uri; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /** * @dev ERC721 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 ERC721Pausable is Pausable, ERC721 { /** * @dev See {ERC721B-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { if (paused()) revert InvalidCall(); super._beforeTokenTransfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INamespaceMinter { /** * @dev Allow admin to mint a name without paying (used for airdrops) */ function mint(address recipient, string memory namespace) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; error InvalidCall(); abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // ============ Storage ============ // Total supply uint256 private _totalSupply; // 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; // ============ Modifiers ============ modifier isToken(uint256 tokenId) { //make sure there is a product if (!_exists(tokenId)) revert InvalidCall(); _; } modifier isNotToken(uint256 tokenId) { //make sure there is a product if (_exists(tokenId)) revert InvalidCall(); _; } // ============ Read Methods ============ /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns(uint256) { if (owner == address(0)) revert InvalidCall(); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override isToken(tokenId) returns(address) { return _owners[tokenId]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns(bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Shows the overall amount of tokens generated in the contract */ function totalSupply() public virtual view returns (uint256) { return _totalSupply; } // ============ Approval Methods ============ /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); if (to == owner) revert InvalidCall(); address sender = _msgSender(); if (sender != owner && !isApprovedForAll(owner, sender)) revert InvalidCall(); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override isToken(tokenId) returns(address) { return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId, address owner) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner( address spender, uint256 tokenId, address owner ) internal view virtual returns(bool) { return spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { if (owner == operator) revert InvalidCall(); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } // ============ Transfer Methods ============ /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _safeTransfer(from, to, tokenId, _data); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} * on a target address. The call is not executed if the target address * is not a contract. */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert InvalidCall(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @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 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, bytes memory _data, bool safeCheck ) internal virtual isNotToken(tokenId) { if (to == address(0)) revert InvalidCall(); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; _totalSupply++; //if do safe check if (safeCheck && to.isContract() && !_checkOnERC721Received(address(0), to, tokenId, _data) ) revert InvalidCall(); emit Transfer(address(0), to, tokenId); } /** * @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 amount) internal virtual { _safeMint(to, amount, ""); } /** * @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 amount, bytes memory _data ) internal virtual { _mint(to, amount, _data, true); } /** * @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); if (to.isContract() && !_checkOnERC721Received(from, to, tokenId, _data) ) { revert InvalidCall(); } } /** * @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 { if (to == address(0)) revert InvalidCall(); //get owner address owner = ERC721.ownerOf(tokenId); //owner should be the `from` if (from != owner) revert InvalidCall(); if (!_isApprovedOrOwner(_msgSender(), tokenId, owner)) revert InvalidCall(); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId, from); unchecked { //this is the situation when _owners are normalized _balances[to] += 1; _balances[from] -= 1; _owners[tokenId] = to; } emit Transfer(from, to, tokenId); } // ============ TODO Methods ============ /** * @dev Hook that is called before a set of serially-ordered token ids * are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * amount - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` * will be transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
Allow admin to mint a name without paying (used for airdrops)/
function mint(address recipient, string memory namespace) external onlyRole(MINTER_ROLE) { _nameMint(recipient, namespace); }
1,639,175
./full_match/1/0x414Cb1508B05e5556650D59d55Ed9A94bFb1A140/sources/contracts/MBS.sol
require(sender != address(0), "ERC20: transfer from the zero address");require(recipient != address(0), "ERC20: transfer to the zero address");
function _transfer(address sender, address recipient, uint256 amount) private { if ((sender == address(0)) || (recipient == address(0))) revert InvalidAddress(); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient] + amount; emit Transfer(sender, recipient, amount); }
4,991,695
./partial_match/1/0x52dAb11c6029862eBF1E65A4d5c30641f5FbD957/sources/AccountLogic.sol
called from 'enter' proposer is backup in the case of 'proposeAsBackup'
function proposeAsBackup(address _backup, address payable _client, bytes calldata _functionData) external allowSelfCallsOnly { bytes4 proposedActionId = getMethodId(_functionData); require(proposedActionId == CHANGE_ADMIN_KEY_BY_BACKUP, "invalid proposal by backup"); checkRelation(_client, _backup); bytes32 functionHash = keccak256(_functionData); accountStorage.setProposalData(_client, _backup, proposedActionId, functionHash, _backup); }
16,014,832
./partial_match/1/0x43c6eE9D5B2369C5484f69E2Eb3361466855beDd/sources/FabricaToken.sol
Updates the current admin address./ _setAdmin() doesn't emit the Upgraded event; _changeAdmin() does.
function setProxyAdmin(address _newProxyAdmin) public onlyProxyAdmin { ERC1967UpgradeUpgradeable._changeAdmin(_newProxyAdmin); }
2,672,087
./partial_match/56/0x743F86115152f12472BF1cA66dd2250A17E81cF1/sources/StrategyCFIBNBLP.sol
Withdraws funds and sents them back to the vault. It withdraws {lpPair} from the ShareRewardPool. The available {lpPair} minus fees is returned to the vault./
function withdraw(uint256 _amount) external { require(msg.sender == vault, "!vault"); uint256 pairBal = IERC20(lpPair).balanceOf(address(this)); if (pairBal < _amount) { IShareRewardPool(shareRewardPool).withdraw(poolId, _amount.sub(pairBal)); pairBal = IERC20(lpPair).balanceOf(address(this)); } if (pairBal > _amount) { pairBal = _amount; } uint256 withdrawalFee = pairBal.mul(WITHDRAWAL_FEE).div(WITHDRAWAL_MAX); IERC20(lpPair).safeTransfer(vault, pairBal.sub(withdrawalFee)); }
11,054,217
pragma solidity =0.8.11; 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; } } 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); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function burn(uint256 amount) external returns (bool); function burnFrom(address account, uint256 amount) external returns (bool); } interface UNIV2Sync { function sync() external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Router { function WETH() external pure returns (address); function factory() external pure returns (address); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IWETH { function deposit() external payable; function balanceOf(address _owner) external returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function withdraw(uint256 _amount) external; } library SafeMath { // Not needed since 0.8 but keeping for backwards compatibility function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _teamWallet; address private _lotteryWallet; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event LotteryWalletTransferred(address indexed previousLotteryWallet, address indexed newLotteryWallet); constructor () { address msgSender = _msgSender(); _teamWallet = msgSender; _lotteryWallet = msgSender; emit OwnershipTransferred(address(0), msgSender); emit LotteryWalletTransferred(address(0), msgSender); } function owner() public view returns (address) { return _teamWallet; } function teamWallet() public view returns (address) { return _teamWallet; } function lotteryWallet() public view returns (address) { return _lotteryWallet; } modifier onlyOwner() { require(_teamWallet == _msgSender(), "Ownable: caller is not the owner or team wallet"); _; } function transferOwnership(address newTeamWallet) public virtual onlyOwner { //don't allow burning except 0xdead require(newTeamWallet != address(0), "Ownable: new teamWallet is the zero address"); emit OwnershipTransferred(_teamWallet, newTeamWallet); _teamWallet = newTeamWallet; } function setLotteryWallet(address newLotteryWallet) public virtual onlyOwner { //don't allow burning except 0xdead require(newLotteryWallet != address(0), "Ownable: new lotteryWallet is the zero address"); emit LotteryWalletTransferred(_lotteryWallet, newLotteryWallet); _lotteryWallet = newLotteryWallet; } } /* * 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 DeflationaryERC20 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; // Transaction Fees uint8 public txFeeBot = 50; // is one-time launch anti-sniper fee, collected tokens will go unsold to _teamWallet uint8 public txFeeTeam = 6; // to _teamWallet for marketing purposes uint8 public txFeeLottery = 4; // to _lotteryWallet for draws uint8 public txFeeLimit = 10; // used as a limit when changing any particular fee bool public txFreeBuys = false; // transactions from the pool are feeless address public uniswapPair; address public uniswapV2RouterAddr; address public uniswapV2wETHAddr; bool private inSwapAndLiquify; event Log (string action); constructor (string memory __name, string memory __symbol, uint8 __decimals) { _name = __name; _symbol = __symbol; _decimals = __decimals; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[msg.sender] = true; //disable for testing fees, enable in production for feeless liquidity add uniswapV2RouterAddr = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //uniswap testnet // uniswapV2RouterAddr = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3; // pancakeswap testnet // uniswapV2RouterAddr = (getChainID() == 56 ? 0x10ED43C718714eb63d5aA57B78B54704E256024E : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // BSC mainnet = 56, else ETH _isExcludedFromFee[uniswapV2RouterAddr] = true; //this will make liquidity removals less expensive uniswapV2wETHAddr = IUniswapV2Router(uniswapV2RouterAddr).WETH(); uniswapPair = IUniswapV2Factory(IUniswapV2Router(uniswapV2RouterAddr).factory()) .createPair(address(this), uniswapV2wETHAddr); } function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory) { return _symbol; } function decimals() external view returns (uint8) { return _decimals; } function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _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) { _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); _transfer(sender, recipient, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function getChainID() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } // to caclulate the amounts for pool and collector after fees have been applied function calculateAmountsAfterFee( address sender, address recipient, uint256 amount ) public view returns (uint256 transferToAmount, uint256 transferToTeamAmount, uint256 transferToLotteryAmount, bool p2p) { // check if fees should apply to this transaction uint256 feeBot = amount.mul(txFeeBot).div(100); //50% then 0% uint256 feeTeam = amount.mul(txFeeTeam).div(100); //6% uint256 feeLottery = amount.mul(txFeeLottery).div(100); //4% // calculate liquidity fees and amounts if any address is an active contract if (sender.isContract() || recipient.isContract()) { return (amount.sub(feeBot).sub(feeTeam).sub(feeLottery), feeBot.add(feeTeam),feeLottery,false); } else { // p2p return (amount, 0, 0, true); } } function burnFrom(address account,uint256 amount) external override returns (bool) { _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); _burn(account, amount); return true; } function burn(uint256 amount) external override returns (bool) { _burn(_msgSender(), amount); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { if (amount == 0) return; require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount >= 100, "amount below 100 base units, avoiding underflows"); _beforeTokenTransfer(sender, recipient, amount); if (inSwapAndLiquify || isExcludedFromFee(sender) || isExcludedFromFee(recipient) || uniswapPair == address(0) || uniswapV2RouterAddr == address(0) || (txFreeBuys == true && sender == uniswapPair)) //feeless transfer before pool initialization and in liquify swap { //send full amount updateBalances(sender, recipient, amount); } else { // calculate fees: (uint256 transferToAmount, uint256 transferToTeamAmount, uint256 transferToLotteryAmount,) = calculateAmountsAfterFee(sender, recipient, amount); // 1: subtract net amount, keep amount for further fees to be subtracted later updateBalances(sender, address(this), transferToTeamAmount.add(transferToLotteryAmount)); //any sell/liquify must occur before main transfer, but avoid that on buys or liquidity removals if (sender != uniswapPair && sender != uniswapV2RouterAddr) // without this buying or removing liquidity to eth fails swapBufferTokens(); // 1: subtract net amount, keep amount for further fees to be subtracted later updateBalances(sender, recipient, transferToAmount); } } function batchTransfer(address payable[] calldata addrs, uint256[] calldata amounts) external returns(bool) { require(amounts.length == addrs.length,"amounts different length from addrs"); for (uint256 i = 0; i < addrs.length; i++) { _transfer(_msgSender(), addrs[i], amounts[i]); } return true; } function batchTransferFrom(address payable[] calldata addrsFrom, address payable[] calldata addrsTo, uint256[] calldata amounts) external returns(bool) { address _currentOwner = _msgSender(); require(addrsFrom.length == addrsTo.length,"addrsFrom different length from addrsTo"); require(amounts.length == addrsTo.length,"amounts different length from addrsTo"); for (uint256 i = 0; i < addrsFrom.length; i++) { _currentOwner = addrsFrom[i]; if (_currentOwner != _msgSender()) { _approve(_currentOwner, _msgSender(), _allowances[_currentOwner][_msgSender()].sub(amounts[i], "ERC20: some transfer amount in batchTransferFrom exceeds allowance")); } _transfer(_currentOwner, addrsTo[i], amounts[i]); } return true; } //Allow excluding from fee certain contracts, usually lock or payment contracts, but not the pool. function excludeFromFee(address account) public onlyOwner { require(account != uniswapPair, 'Cannot exclude Uniswap pair'); _isExcludedFromFee[account] = true; } // Do not include back this contract. function includeInFee(address account) public onlyOwner { require(account != address(this),'Cannot enable fees to the token contract itself'); _isExcludedFromFee[account] = false; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function swapBufferTokens() private { if (inSwapAndLiquify) // prevent reentrancy return; uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance <= _totalSupply.div(1e9)) //only swap reasonable amounts return; if (contractTokenBalance <= 100) //do not swap too small amounts return; // swap tokens for ETH to the contract if (txFeeBot > txFeeLimit) { updateBalances(address(this), teamWallet(), contractTokenBalance); } else { inSwapAndLiquify = true; swapTokensForEth(contractTokenBalance); // avoid reentrancy here inSwapAndLiquify = false; uint256 contractETHBalance = address(this).balance; uint256 half = contractETHBalance.div(txFeeTeam+txFeeLottery).mul(txFeeTeam); uint256 otherHalf = contractETHBalance.sub(half); payable(teamWallet()).transfer(half); payable(lotteryWallet()).transfer(otherHalf); } } 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] = uniswapV2wETHAddr; _approve(address(this), uniswapV2RouterAddr, tokenAmount); // make the swap but never fail try IUniswapV2Router(uniswapV2RouterAddr).swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ) {} catch Error(string memory reason) {emit Log(reason);} } function updateBalances(address _from, address _to, uint256 _amount) internal { // do nothing on self transfers and zero transfers if (_from != _to && _amount > 0) { _balances[_from] = _balances[_from].sub(_amount, "ERC20: transfer amount exceeds balance"); _balances[_to] = _balances[_to].add(_amount); emit Transfer(_from, _to, _amount); } } function setTxTeamFeePercent(uint8 _txFeeTeam) external onlyOwner() { require(_txFeeTeam <= txFeeLimit,'txFeeTeam above limit'); txFeeTeam = _txFeeTeam; } function setTxLotteryFeePercent(uint8 _txFeeLottery) external onlyOwner() { require(_txFeeLottery <= txFeeLimit,'txFeeLottery above limit'); txFeeLottery = _txFeeLottery; } function setTxFeeBotFeePercent(uint8 _txFeeBot) external onlyOwner() { require(_txFeeBot == 0,'txFeeBot above zero'); swapBufferTokens(); txFeeBot = _txFeeBot; } function setTxFreeBuys(bool _txFreeBuys) external onlyOwner() { txFreeBuys = _txFreeBuys; } function _mint(address account, uint256 amount) internal virtual { require(_totalSupply == 0, "Mint: Not an initial supply mint"); 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); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); if(amount != 0) { _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * Hook that is called before any transfer of tokens. This includes minting and burning. * 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 { } //sennding ether to this contract will succeed and the ether will later move to the collector receive() external payable { //revert(); } function transferAnyTokens(address _tokenAddr, address _to, uint _amount) external onlyOwner { //the owner takes it anyway, sold or unsold //require(_tokenAddr != address(this), "Cannot transfer out from sell/liquify queue!"); IERC20(_tokenAddr).transfer(_to, _amount); uint256 amountETH = address(this).balance; if (amountETH > 0) { IWETH(uniswapV2wETHAddr).deposit{value : amountETH}(); //send weth to collector, this is to avoid reverts if collector is a contract IWETH(uniswapV2wETHAddr).transfer(owner(), amountETH); } } } // contract FlokiGainzToken is DeflationaryERC20 { // constructor() DeflationaryERC20("FlokiGainz", "GAINZ", 6) { // // maximum supply = 500m with decimals = 6 // _mint(msg.sender, 500e12); // } // } // File: floki.sol //SPDX-License-Identifier: MIT pragma solidity =0.8.11; contract FlokiGainzToken is DeflationaryERC20 { constructor(address _owner) DeflationaryERC20("FlokiGainz", "GAINZ", 6) { // maximum supply = 500m with decimals = 6 _mint(_owner, 500e12); transferOwnership(_owner); } }
do nothing on self transfers and zero transfers
function updateBalances(address _from, address _to, uint256 _amount) internal { if (_from != _to && _amount > 0) { _balances[_from] = _balances[_from].sub(_amount, "ERC20: transfer amount exceeds balance"); _balances[_to] = _balances[_to].add(_amount); emit Transfer(_from, _to, _amount); } }
11,907,328
pragma solidity ^0.4.20; contract XToken { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[(_customerAddress)]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won&#39;t reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "X Token"; string public symbol = "XTK"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 5; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 0.3 ether; uint256 constant internal ambassadorQuota_ = 3 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function XToken() public { // add administrators here administrators[msg.sender] = true; // add the ambassadors here. // ambassadors_[0xEc31176d4df0509115abC8065A8a3F8275aafF2b] = true; // ambassadors_[0xd5fa3017a6af76b31eb093dfa527ee1d939f05ea] = true; // ambassadors_[0x6629c7199ecc6764383dfb98b229ac8c540fc76f] = true; // ambassadors_[0x2De78Fbc7e1D1c93aa5091aE28dd836CC71e8d4c] = true; // ambassadors_[0x41e8cee8068eb7344d4c61304db643e68b1b7155] = true; // ambassadors_[0xcec269b2c42931f43e3e08c0f20faa6e6a9cb2ff] = true; // ambassadors_[0xee54d208f62368b4effe176cb548a317dcae963f] = true; // ambassadors_[0x008ca4f1ba79d1a265617c6206d7884ee8108a78] = true; // ambassadors_[0x2BC9aAe6d3Ac1396740CF4854AD8121940eA98c0] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there&#39;s a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can&#39;t give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; //really i know you think you do but you don&#39;t int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#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; } }
-- APPLICATION ENTRY POINTS --/ add administrators here add the ambassadors here.
function XToken() public { administrators[msg.sender] = true; ambassadors_[0xEc31176d4df0509115abC8065A8a3F8275aafF2b] = true; ambassadors_[0xd5fa3017a6af76b31eb093dfa527ee1d939f05ea] = true; ambassadors_[0x6629c7199ecc6764383dfb98b229ac8c540fc76f] = true; ambassadors_[0x2De78Fbc7e1D1c93aa5091aE28dd836CC71e8d4c] = true; ambassadors_[0x41e8cee8068eb7344d4c61304db643e68b1b7155] = true; ambassadors_[0xcec269b2c42931f43e3e08c0f20faa6e6a9cb2ff] = true; ambassadors_[0xee54d208f62368b4effe176cb548a317dcae963f] = true; ambassadors_[0x008ca4f1ba79d1a265617c6206d7884ee8108a78] = true; ambassadors_[0x2BC9aAe6d3Ac1396740CF4854AD8121940eA98c0] = true; }
10,914,763
./full_match/1/0xbA75e25e387A577930fD7180Ad67D0b9F7917880/sources/browser/btp.sol
Ensure transparency by hardcoding limit beyond which fees can never be added
function setParams(uint256 newBasisPoints, uint256 newMaxFee) public onlyOwner { require(newBasisPoints <= 20); require(newMaxFee <= 50); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(uint256(10)**decimals); emit Params(basisPointsRate, maximumFee); }
3,107,086
./full_match/1/0x7225244B17051c76c8C758EAf3F7bb4d0Fc953bA/sources/contracts/YeyeVault.sol
store traits of equipped token to vault/
function storeTraits(address owner, uint256[] memory ids) external onlyRole(OWNER_ROLE) { require(owner != address(0), "VAULT ERROR: store to zero address"); uint256[] memory values = getRange(ids.length, 1); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; _traitBalances[id][owner] += 1; } emit TraitTransfer(_msgSender(), address(0), owner, ids, values); }
5,005,372
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @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: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); 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 data ) public; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 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 data ) public returns(bytes4); } // 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; } } // File: openzeppelin-solidity/contracts/utils/Address.sol /** * 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. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private 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) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private 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)')) */ constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @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 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 * Reverts if the token ID does not exist. * @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) { require(_exists(tokenId)); 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(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 _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @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) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @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 add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @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 * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @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 _checkOnERC721Received( address from, address to, uint256 tokenId, bytes _data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private 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) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable is IERC721 { 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); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor() public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @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 add a token ID to the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @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 * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @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); // 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: openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Metadata is IERC721 { function name() external view returns (string); function symbol() external view returns (string); function tokenURI(uint256 tokenId) external view returns (string); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor(string name, string symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { 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) external view returns (string) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @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 uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @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]; } } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol /** * @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 ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor(string name, string symbol) ERC721Metadata(name, symbol) public { } } // File: contracts/Referrers.sol contract Referrers is Ownable { using SafeMath for uint256; // Referrer bonus in % uint public referrerBonusSale; uint public referrerBonusWin; uint public _referrerId; // mapping referrerId to address mapping(uint => address) public referrerToAddress; // Tickets referals: tokeId => referrerId mapping(uint => uint) public ticketToReferrer; // Tickets of referrer mapping(uint => uint[]) public referrerTickets; // mapping address to referrerId mapping(address => uint) public addressToReferrer; mapping(uint => uint) public totalEarnReferrer; constructor() public { referrerBonusSale = 8; referrerBonusWin = 2; _referrerId = 0; } function _setTicketReferrer(uint _tokenId, uint _referrer) internal { require(ticketToReferrer[_tokenId] == 0); ticketToReferrer[_tokenId] = _referrer; referrerTickets[_referrer].push(_tokenId); } function registerReferrer() public { require(addressToReferrer[msg.sender] == 0); _referrerId = _referrerId.add(1); addressToReferrer[msg.sender] = _referrerId; referrerToAddress[_referrerId] = msg.sender; } function getReferrerTickets(uint _referrer) public view returns (uint[]) { return referrerTickets[_referrer]; } // Admin methods function setReferrerBonusWin(uint _amount) public onlyOwner { referrerBonusWin = _amount; } function setReferrerBonusSale(uint _amount) public onlyOwner { referrerBonusSale = _amount; } //End admin methods } // File: contracts/Utils.sol library Utils { function pack(uint[] _data) internal pure returns(uint) { uint result = 0; for (uint i=0;i<_data.length;i++) { result += 2**_data[i]; } return result; } function unpack(uint _data, uint _maxBallsCount) internal pure returns(uint[]) { uint[] memory result = new uint256[](_maxBallsCount); uint iPosition = 0; uint i = 0; while (_data != 0) { if ((_data & 1) == 1) { result[iPosition] = i; iPosition++; } i++; _data >>= 1; } return result; } function popcount(uint x) public pure returns(uint) { uint count; for (count=0; x > 0; count++) { x &= x - 1; } return count; } function getBonusAmount(uint _amount, uint _bonusPercent) internal pure returns (uint) { return _amount * _bonusPercent / 100; } function addr2str(address _addr) internal pure returns(string) { bytes32 value = bytes32(uint256(_addr)); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(42); str[0] = '0'; str[1] = 'x'; for (uint i = 0; i < 20; i++) { str[2+i*2] = alphabet[uint(value[i + 12] >> 4)]; str[3+i*2] = alphabet[uint(value[i + 12] & 0x0f)]; } return string(str); } } // File: contracts/Balance.sol library Balance { using SafeMath for uint256; struct BalanceStorage { // users/referrals balances mapping(address => uint) balances; mapping(address => uint) totalEarn; } // Add amount wei to address balance function _addBalance(BalanceStorage storage self, address _address, uint _amount) internal { self.balances[_address] = self.balances[_address].add(_amount); self.totalEarn[_address] = self.totalEarn[_address].add(_amount); } function _subBalance(BalanceStorage storage self, address _address, uint _amount) internal { self.balances[_address] = self.balances[_address].sub(_amount); self.totalEarn[_address] = self.totalEarn[_address].sub(_amount); } function _clearBalance(BalanceStorage storage self, address _address) internal { self.balances[_address] = 0; } function _getBalance(BalanceStorage storage self, address _address) internal view returns (uint){ return self.balances[_address]; } function _getTotalEarn(BalanceStorage storage self, address _address) internal view returns (uint){ return self.totalEarn[_address]; } } // File: contracts/CryptoBall645.sol //Write your own contracts here. Currently compiles using solc v0.4.15+commit.bbb8e64f. pragma solidity ^0.4.25; contract DrawContractI { function ticketToDraw(uint _tokenId) public returns (uint); function drawNumber() public returns (uint); function drawTime(uint _drawNumber) public returns (uint); function ticketPrizes(uint _tokenId) public returns (uint); function registerTicket(uint _tokenId, uint[] _numbers, uint _ticketPrice, uint _ownerBonusSale, uint _referrerBonusSale, uint _drawNumber) external; function checkTicket(uint _tokenId) external; function addSuperPrize(uint _amount) external; } contract CryptoBall645 is ERC721Full("Crypto balls 6/45", "B645"), Ownable, Referrers { using Balance for Balance.BalanceStorage; Balance.BalanceStorage balance; event OwnerBonus(address indexed _to, uint _amount); event ReferrerBonus(address indexed _to, uint _amount); using SafeMath for uint256; uint constant public MAX_BALLS_COUNT = 6; uint constant public MAX_BALL_NUMBER = 45; //Bonus of contract owner uint public ownerBonusSale = 25; uint public ownerBonusWin = 0; uint public ticketPrice = 0.01 ether; uint public tokenIds = 0; mapping(uint => uint) public mintDate; DrawContractI drawContract; address public drawContractAddress; modifier onlyDrawContract() { require(msg.sender == drawContractAddress); _; } modifier allowBuyTicket() { require(msg.value == ticketPrice); _; } modifier allowBuyTicketCount(uint _drawCount) { require(msg.value == ticketPrice*_drawCount); _; } modifier allowRegisterTicket(uint[] _numbers) { require(_numbers.length == MAX_BALLS_COUNT); for (uint i = 0; i < MAX_BALLS_COUNT; i++) { require(_numbers[i] > 0); require(_numbers[i] <= MAX_BALL_NUMBER); for (uint t = 0; t < MAX_BALLS_COUNT; t++) { if (t == i) { continue; } require(_numbers[t]!=_numbers[i]); } } _; } /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } // Update ticket price function setTicketPrice(uint _amount) external onlyOwner { ticketPrice = _amount; } // Update sale bonus for owner function setOwnerBonusSale(uint _amount) external onlyOwner { ownerBonusSale = _amount; } // Update win bonus for owner function setOwnerBonusWin(uint _amount) external onlyOwner { ownerBonusWin = _amount; } function setDrawContract(address _address) public onlyOwner { drawContractAddress = _address; drawContract = DrawContractI(_address); } function burn(uint _tokenId) external onlyOwner { require((now - mintDate[_tokenId]) / 60 / 60 / 24 > 30); require(drawContract.ticketToDraw(_tokenId) == 0); uint _refundPrice = ticketPrice * (100 - ownerBonusSale - referrerBonusSale) / 100; balance._addBalance(owner(), _refundPrice); _burn(ownerOf(_tokenId), _tokenId); } // Tokens list of user function getMyTickets() public view returns (uint256[]) { uint _myTotalTokens = balanceOf(msg.sender); uint[] memory _myTokens = new uint[](_myTotalTokens); uint k = 0; for (uint i = 0; i <= totalSupply(); i++) { uint _myTokenId = tokenOfOwnerByIndex(msg.sender, i); if (_myTokenId > 0) { _myTokens[k] = _myTokenId; k++; if (k >= _myTotalTokens) { break; } } } return _myTokens; } // Buy ticket function _buyToken(address _to, uint _referrerId) private returns (uint) { tokenIds = tokenIds.add(1); uint _tokenId = tokenIds; _mint(_to, _tokenId); transferFrom(ownerOf(_tokenId), msg.sender, _tokenId); mintDate[_tokenId] = now; // Send bonus to the owner _addOwnerBonus(ticketPrice, ownerBonusSale); // Send bonus to the referrer if referrerId was sent and referrer was registered if (_referrerId == 0) { _referrerId = addressToReferrer[owner()]; } if (_referrerId > 0 && referrerToAddress[_referrerId] > 0) { _addReferrerBonus(_referrerId, ticketPrice, referrerBonusSale); _setTicketReferrer(_tokenId, _referrerId); } return _tokenId; } function() public payable { require(msg.value >= ticketPrice); uint ticketsCount = msg.value / ticketPrice; uint returnCount = msg.value % ticketPrice; if (returnCount > 0) { msg.sender.transfer(returnCount); } for (uint i = 1; i <= ticketsCount; i++) { _buyToken(msg.sender, 0); } } // User buy new ticket function buyTicket(uint _referrerId) public payable allowBuyTicket { _buyToken(msg.sender, _referrerId); } // Buy, fill and register ticket function buyAndRegisterTicket(uint _referrerId, uint[] _numbers, uint _drawCount) public payable allowBuyTicketCount(_drawCount) allowRegisterTicket(_numbers) returns (uint){ uint _drawNumber = drawContract.drawNumber(); for (uint i = 0; i<_drawCount; i++) { uint _tokenId = _buyToken(msg.sender, _referrerId); uint _draw = _drawNumber + i; drawContract.registerTicket(_tokenId, _numbers, ticketPrice, ownerBonusSale, referrerBonusSale, _draw); } } // Register ticket to the nearest drawing function registerTicket(uint _tokenId, uint[] _numbers, uint _drawNumber) public onlyOwnerOf(_tokenId) allowRegisterTicket(_numbers) { //Ticket not yet filled require(drawContract.ticketToDraw(_tokenId) == 0); drawContract.registerTicket(_tokenId, _numbers, ticketPrice, ownerBonusSale, referrerBonusSale, _drawNumber); } function _checkTicket(uint _tokenId, address _receiver) private returns (bool) { drawContract.checkTicket(_tokenId); uint _prize = drawContract.ticketPrizes(_tokenId); if (_prize > 0) { if (_prize == ticketPrice) { _buyToken(_receiver, ticketToReferrer[_tokenId]); balance._subBalance(owner(), ticketPrice); } else { _addPriceToBalance(_tokenId, _prize, _receiver); } } return true; } // Check ticket and move prize to balance function checkTicket(uint _tokenId) public { require(_exists(_tokenId)); require(_checkTicket(_tokenId, ownerOf(_tokenId))); } // Contract owner can withdraw prizes after 30 days if winner didn't withdraw it function withdrawTicketPrize(uint _tokenId) public onlyOwner { require(_exists(_tokenId)); uint _ticketDraw = drawContract.ticketToDraw(_tokenId); require((now - drawContract.drawTime(_ticketDraw)) / 60 / 60 / 24 > 30); require(_checkTicket(_tokenId, owner())); } function _addPriceToBalance(uint _tokenId, uint _prizeAmount, address _receiver) private { uint _ownerBonus = Utils.getBonusAmount(_prizeAmount, ownerBonusWin); uint _referrerBonus = Utils.getBonusAmount(_prizeAmount, referrerBonusWin); uint _referrerId = ticketToReferrer[_tokenId]; uint winnerPrizeAmount = _prizeAmount - _ownerBonus - _referrerBonus; balance._addBalance(_receiver, winnerPrizeAmount); _addReferrerBonus(_referrerId, winnerPrizeAmount, referrerBonusWin); _addOwnerBonus(winnerPrizeAmount, ownerBonusWin); } // Get My balance function getMyBalance() public view returns (uint){ return balance._getBalance(msg.sender); } // Withdraw My balance function withdrawMyBalance() public { uint _userBalance = balance._getBalance(msg.sender); require(_userBalance > 0); require(address(this).balance >= _userBalance); balance._clearBalance(msg.sender); msg.sender.transfer(_userBalance); emit Transfer(this, msg.sender, _userBalance); } function withdrawBalanceAmount(uint _amount) public { uint _userBalance = balance._getBalance(msg.sender); require(_userBalance > 0); require(_amount <= _userBalance); require(address(this).balance >= _amount); balance._subBalance(msg.sender, _amount); msg.sender.transfer(_amount); emit Transfer(this, msg.sender, _amount); } function _addReferrerBonus(uint _referrer, uint _fromAmount, uint _bonusPercent) internal { address _referrerAddress = referrerToAddress[_referrer]; if (_referrerAddress == address(0)) { _referrerAddress = owner(); } uint _amount = Utils.getBonusAmount(_fromAmount, _bonusPercent); if (_amount > 0) { balance._addBalance(_referrerAddress, _amount); totalEarnReferrer[_referrer] = totalEarnReferrer[_referrer].add(_amount); emit ReferrerBonus(_referrerAddress, _amount); } } function _addOwnerBonus(uint _fromAmount, uint _bonusPercent) internal { uint _amount = Utils.getBonusAmount(_fromAmount, _bonusPercent); if (_amount > 0) { balance._addBalance(owner(), _amount); emit OwnerBonus(owner(), _amount); } } function addBalance(address _address, uint _amount) external onlyDrawContract { balance._addBalance(_address, _amount); } function addSuperPrize() public payable { drawContract.addSuperPrize(msg.value); } }
Register ticket to the nearest drawingTicket not yet filled
function registerTicket(uint _tokenId, uint[] _numbers, uint _drawNumber) public onlyOwnerOf(_tokenId) allowRegisterTicket(_numbers) { require(drawContract.ticketToDraw(_tokenId) == 0); drawContract.registerTicket(_tokenId, _numbers, ticketPrice, ownerBonusSale, referrerBonusSale, _drawNumber); }
12,689,457
./full_match/43113/0xC5265Ff869A22E0A58697898920607e441E1B37F/sources/contracts/drawax.sol
return the one who found the exact number or nearest number of randomResult 1. the one who found the exact number 4. pay all user who choose multiple of random result and > 20
function findWinner(uint256 randomResult) internal returns(address) { if (_gameGrid[randomResult] != _START_ADDRESS) { _winner = payable(_gameGrid[randomResult]); _winners.push( Winner(_pool, _players[_winner].pseudo, _winner, randomResult, randomResult, _launchDay + _DRAW_DAYS)); emit NewWinner(randomResult, _players[_winner]); require(success, "Failed to send money"); _poolPrice += _pool * 60 / 100; return _winner; } while (i > 0) { if (_gameGrid[i] != _START_ADDRESS) { _winner = payable(_gameGrid[i]); _winners.push( Winner(_pool, _players[_winner].pseudo, _winner, randomResult, i, _launchDay + _DRAW_DAYS)); emit NewWinner(randomResult, _players[_winner]); require(success, "Failed to send money"); _poolPrice += _pool * 50 / 100; return _winner; } i -= 1; } _winners.push( Winner(_pool, _players[_START_ADDRESS].pseudo, _winner, randomResult, randomResult, _launchDay + _DRAW_DAYS)); emit NewWinner(randomResult, _players[_START_ADDRESS]); if (randomResult > 20) { for (uint256 j = 20; j > _MAX_NUMBER; j++) { if (j % randomResult == 0 && _gameGrid[j] != _START_ADDRESS) { _winner = payable(_gameGrid[j]); require(success, "Failed to send money"); emit MultipleFinder(_winner, _players[_winner].pseudo); _poolPrice += _pool * 2 / 1000; } } } return _START_ADDRESS; }
7,196,977
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "./opensea/IERC1155.sol"; import "./Ownable.sol"; /// @author Santiago Del Valle <[email protected]> contract Game is Ownable, IERC1155Receiver { using SafeMath for uint256; event NewWinner(address indexed _winner, uint256 tokenId); IERC721 public groupies; IERC1155 public tokenERC1155; bytes32 private _solution; uint256 private _tokenId; uint8 private _x; uint8 private _y; bool private _paused; mapping(address => bool) public walletHasPlayed; constructor(address groupies_, address tokenERC1155_, address owner_) Ownable(owner_) { groupies = IERC721(groupies_); tokenERC1155 = IERC1155(tokenERC1155_); } /****************Setters****************** */ function setGameParams(uint8 x_, uint8 y_, uint256 tokenId_, string memory solution_) external onlyOwner { _x = x_; _y = y_; _tokenId = tokenId_; _solution = sha256(abi.encode(solution_)); } function setERC1155Address(address tokenERC1155_) external onlyOwner { tokenERC1155 = IERC1155(tokenERC1155_); } function pauseGame(bool pause_) external onlyOwner { _paused = pause_; } /***************Getters *******************/ function getGameParams() external view returns (uint8, uint8, uint256) { return ( _x, _y, _tokenId ); } /**************Game Logic****************/ function transferERC1155(address to_, uint256 tokenId_, uint256 amount_) external onlyOwner { tokenERC1155.safeTransferFrom(address(this), to_, tokenId_, amount_, ""); } function claimTokenWithSolution(string memory incomingSolution_) public { require(!_paused, "Game is paused"); require(groupiesBalanceOf(_msgSender()) > 0, "No groupies balance"); require(!walletHasPlayed[_msgSender()], "Wallet has already played"); require(_solution == sha256(abi.encode(incomingSolution_)), "Wrong solution"); walletHasPlayed[_msgSender()] = true; tokenERC1155.safeTransferFrom(address(this), _msgSender(), _tokenId, 1, ""); emit NewWinner(_msgSender(), _tokenId); } function groupiesBalanceOf(address account_) public view returns (uint256) { return groupies.balanceOf(account_); } /**********Support for TokenERC1155 when transfering a token to this contract */ function onERC1155Received( address /* operator */, address /* from */, uint256 /* id */, uint256 /* value */, bytes calldata /* data */ ) external override pure returns (bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } function onERC1155BatchReceived( address /* operator */, address /* from */, uint256[] calldata /* ids */, uint256[] calldata /* values */, bytes calldata /* data */ ) external override pure returns (bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")); } function supportsInterface(bytes4 /*interfaceId*/) external override pure returns (bool) { return false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts//utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(address newOwner) { _setOwner(newOwner); } /** * @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 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: Apache-2.0 pragma solidity ^0.8.0; 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); /****************************************| | Functions | |_______________________________________*/ /** * @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 isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } // 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 (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: 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. * * NOTE: 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 // 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; } } } // 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/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); }
Setters /
function setGameParams(uint8 x_, uint8 y_, uint256 tokenId_, string memory solution_) external onlyOwner { _x = x_; _y = y_; _tokenId = tokenId_; _solution = sha256(abi.encode(solution_)); }
13,908,308
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; //import {SafeMathUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol'; import {IERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import {IERC20Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import {SafeERC20Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol'; import {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol'; import {Decimal} from './Decimal.sol'; import {ZapMedia} from './ZapMedia.sol'; import {IMarket} from './interfaces/IMarket.sol'; import {Ownable} from './access/Ownable.sol'; /** * @title A Market for pieces of media * @notice This contract contains all of the market logic for Media */ contract ZapMarket is IMarket, Ownable { using SafeERC20Upgradeable for IERC20Upgradeable; /* ******* * Globals * ******* */ // Address of the media contract that can call this market mapping(address => address[]) public mediaContracts; // Mapping from media address to a bool showing whether or not // they're registered by the media factory mapping(address => bool) public registeredMedias; // registered media factory address address mediaFactory; // Mapping from token to mapping from bidder to bid mapping(address => mapping(uint256 => mapping(address => Bid))) private _tokenBidders; // Mapping from token to the bid shares for the token mapping(address => mapping(uint256 => BidShares)) private _bidShares; // Mapping from token to the current ask for the token mapping(address => mapping(uint256 => Ask)) private _tokenAsks; // Mapping from Media address to the Market configuration status mapping(address => bool) public isConfigured; // Mapping of token ids of accepted bids to their mutex mapping(uint256 => bool) private bidMutex; address platformAddress; IMarket.PlatformFee platformFee; /* ********* * Modifiers * ********* */ /** * @notice require that the msg.sender is the configured media contract */ modifier onlyMediaCaller() { require( isConfigured[msg.sender] == true, 'Market: Only media contract' ); _; } modifier onlyMediaFactory() { require( msg.sender == mediaFactory, 'Market: Only the media factory can do this action' ); _; } modifier isUnlocked(uint256 tokenId) { require(!bidMutex[tokenId], 'There is a bid transaction in progress'); bidMutex[tokenId] = true; _; bidMutex[tokenId] = false; } /* **************** * View Functions * **************** */ function bidForTokenBidder( address mediaContractAddress, uint256 tokenId, address bidder ) external view override returns (Bid memory) { return _tokenBidders[mediaContractAddress][tokenId][bidder]; } function currentAskForToken(address mediaContractAddress, uint256 tokenId) external view override returns (Ask memory) { return _tokenAsks[mediaContractAddress][tokenId]; } function bidSharesForToken(address mediaContractAddress, uint256 tokenId) public view override returns (BidShares memory) { return _bidShares[mediaContractAddress][tokenId]; } /** * @notice Validates that the bid is valid by ensuring that the bid amount can be split perfectly into all the bid shares. * We do this by comparing the sum of the individual share values with the amount and ensuring they are equal. Because * the splitShare function uses integer division, any inconsistencies with the original and split sums would be due to * a bid splitting that does not perfectly divide the bid amount. */ function isValidBid( address mediaContractAddress, uint256 tokenId, uint256 bidAmount ) public view override returns (bool) { BidShares memory bidShares = bidSharesForToken( mediaContractAddress, tokenId ); require( isValidBidShares(bidShares), 'Market: Invalid bid shares for token' ); uint256 collabShareValue = 0; Decimal.D256 memory thisCollabsShare; thisCollabsShare.value = 0; for (uint256 i = 0; i < bidShares.collaborators.length; i++) { thisCollabsShare.value = bidShares.collabShares[i]; collabShareValue = collabShareValue + (splitShare(thisCollabsShare, bidAmount)); } return bidAmount != 0 && (bidAmount == splitShare(bidShares.creator, bidAmount) + (collabShareValue) + (splitShare(platformFee.fee, bidAmount)) + (splitShare(bidShares.owner, bidAmount))); } /** * @notice Validates that the provided bid shares sum to 100 */ function isValidBidShares(BidShares memory bidShares) public view override returns (bool) { uint256 collabSharePerc = 0; for (uint256 i = 0; i < bidShares.collaborators.length; i++) { collabSharePerc = collabSharePerc + (bidShares.collabShares[i]); } return bidShares.creator.value + (collabSharePerc) + (bidShares.owner.value) + (platformFee.fee.value) == uint256(100) * (Decimal.BASE); } /** * @notice return a % of the specified amount. This function is used to split a bid into shares * for a media's shareholders. */ function splitShare(Decimal.D256 memory sharePercentage, uint256 amount) public pure override returns (uint256) { return Decimal.mul(amount, sharePercentage) / (100); } /* **************** * Public Functions * **************** */ function initializeMarket(address _platformAddress) public initializer { owner = msg.sender; platformAddress = _platformAddress; } function isRegistered(address mediaContractAddress) public view override returns (bool) { return (registeredMedias[mediaContractAddress]); } function setMediaFactory(address _mediaFactory) external override onlyOwner { mediaFactory = _mediaFactory; } function viewFee() public view returns (Decimal.D256 memory) { return platformFee.fee; } function setFee(IMarket.PlatformFee memory newFee) public onlyOwner { platformFee = newFee; } /** * @notice Sets the media contract address. This address is the only permitted address that * can call the mutable functions. This method can only be called once. */ function configure( address deployer, address mediaContract, bytes32 name, bytes32 symbol ) external override onlyMediaFactory { require( isConfigured[mediaContract] != true, 'Market: Already configured' ); require( mediaContract != address(0) && deployer != address(0), 'Market: cannot set media contract as zero address' ); isConfigured[mediaContract] = true; mediaContracts[deployer].push(mediaContract); emit MediaContractCreated(mediaContract, name, symbol); } function mintOrBurn( bool isMint, uint256 tokenId, address mediaContract ) external override { require(msg.sender == mediaContract, 'Market: Media only function'); if (isMint == true) { emit Minted(tokenId, mediaContract); } else { emit Burned(tokenId, mediaContract); } } function registerMedia(address mediaContract) external override onlyMediaFactory { registeredMedias[mediaContract] = true; } function revokeRegistration(address mediaContract) external override onlyOwner { registeredMedias[mediaContract] = false; } /** * @notice Sets bid shares for a particular tokenId. These bid shares must * sum to 100. */ function setBidShares(uint256 tokenId, BidShares memory bidShares) public override onlyMediaCaller { require( isValidBidShares(bidShares), 'Market: Invalid bid shares, must sum to 100' ); _bidShares[msg.sender][tokenId] = bidShares; emit BidShareUpdated(tokenId, bidShares, msg.sender); } /** * @notice Sets the ask on a particular media. If the ask cannot be evenly split into the media's * bid shares, this reverts. */ function setAsk(uint256 tokenId, Ask memory ask) public override onlyMediaCaller { require( isValidBid(msg.sender, tokenId, ask.amount), 'Market: Ask invalid for share splitting' ); _tokenAsks[msg.sender][tokenId] = ask; emit AskCreated(msg.sender, tokenId, ask); } /** * @notice removes an ask for a token and emits an AskRemoved event */ function removeAsk(uint256 tokenId) external override onlyMediaCaller { emit AskRemoved(tokenId, _tokenAsks[msg.sender][tokenId], msg.sender); delete _tokenAsks[msg.sender][tokenId]; } /** * @notice Sets the bid on a particular media for a bidder. The token being used to bid * is transferred from the spender to this contract to be held until removed or accepted. * If another bid already exists for the bidder, it is refunded. */ function setBid( uint256 tokenId, Bid memory bid, address spender ) public override onlyMediaCaller { BidShares memory bidShares = _bidShares[msg.sender][tokenId]; require( bidShares.creator.value + (bid.sellOnShare.value) <= uint256(100) * (Decimal.BASE), 'Market: Sell on fee invalid for share splitting' ); require(bid.bidder != address(0), 'Market: bidder cannot be 0 address'); require(bid.amount != 0, 'Market: cannot bid amount of 0'); require( bid.currency != address(0), 'Market: bid currency cannot be 0 address' ); require( bid.recipient != address(0), 'Market: bid recipient cannot be 0 address' ); Bid storage existingBid = _tokenBidders[msg.sender][tokenId][ bid.bidder ]; // If there is an existing bid, refund it before continuing if (existingBid.amount > 0) { removeBid(tokenId, bid.bidder); } IERC20Upgradeable token = IERC20Upgradeable(bid.currency); // We must check the balance that was actually transferred to the market, // as some tokens impose a transfer fee and would not actually transfer the // full amount to the market, resulting in locked funds for refunds & bid acceptance uint256 beforeBalance = token.balanceOf(address(this)); token.safeTransferFrom(spender, address(this), bid.amount); require( token.balanceOf(address(this)) == beforeBalance + bid.amount, 'Market: Market balance did not increase from bid' ); _tokenBidders[msg.sender][tokenId][bid.bidder] = Bid( bid.amount, bid.currency, bid.bidder, bid.recipient, bid.sellOnShare ); emit BidCreated(msg.sender, tokenId, bid); // If a bid meets the criteria for an ask, automatically accept the bid. // If no ask is set or the bid does not meet the requirements, ignore. if ( _tokenAsks[msg.sender][tokenId].currency != address(0) && bid.currency == _tokenAsks[msg.sender][tokenId].currency && bid.amount >= _tokenAsks[msg.sender][tokenId].amount ) { // Finalize exchange _finalizeNFTTransfer(msg.sender, tokenId, bid.bidder); } } /** * @notice Removes the bid on a particular media for a bidder. The bid amount * is transferred from this contract to the bidder, if they have a bid placed. */ function removeBid(uint256 tokenId, address bidder) public override onlyMediaCaller isUnlocked(tokenId) { Bid storage bid = _tokenBidders[msg.sender][tokenId][bidder]; uint256 bidAmount = bid.amount; address bidCurrency = bid.currency; require(bid.amount > 0, 'Market: cannot remove bid amount of 0'); IERC20Upgradeable token = IERC20Upgradeable(bidCurrency); emit BidRemoved(tokenId, bid, msg.sender); delete _tokenBidders[msg.sender][tokenId][bidder]; token.safeTransfer(bidder, bidAmount); } /** * @notice Accepts a bid from a particular bidder. Can only be called by the media contract. * See {_finalizeNFTTransfer} * Provided bid must match a bid in storage. This is to prevent a race condition * where a bid may change while the acceptBid call is in transit. * A bid cannot be accepted if it cannot be split equally into its shareholders. * This should only revert in rare instances (example, a low bid with a zero-decimal token), * but is necessary to ensure fairness to all shareholders. */ function acceptBid( address mediaContractAddress, uint256 tokenId, Bid calldata expectedBid ) external override onlyMediaCaller isUnlocked(tokenId) { Bid memory bid = _tokenBidders[mediaContractAddress][tokenId][ expectedBid.bidder ]; require(bid.amount > 0, 'Market: cannot accept bid of 0'); require( bid.amount == expectedBid.amount && bid.currency == expectedBid.currency && bid.sellOnShare.value == expectedBid.sellOnShare.value && bid.recipient == expectedBid.recipient, 'Market: Unexpected bid found.' ); require( isValidBid(mediaContractAddress, tokenId, bid.amount), 'Market: Bid invalid for share splitting' ); _finalizeNFTTransfer(mediaContractAddress, tokenId, bid.bidder); } /** * @notice Given a token ID and a bidder, this method transfers the value of * the bid to the shareholders. It also transfers the ownership of the media * to the bid recipient. Finally, it removes the accepted bid and the current ask. */ function _finalizeNFTTransfer( address mediaContractAddress, uint256 tokenId, address bidder ) private { Bid memory bid = _tokenBidders[mediaContractAddress][tokenId][bidder]; BidShares storage bidShares = _bidShares[mediaContractAddress][tokenId]; IERC20Upgradeable token = IERC20Upgradeable(bid.currency); // Transfer bid share to owner of media token.safeTransfer( IERC721Upgradeable(mediaContractAddress).ownerOf(tokenId), splitShare(bidShares.owner, bid.amount) ); // Transfer bid share to creator of media token.safeTransfer( ZapMedia(mediaContractAddress).getTokenCreators(tokenId), splitShare(bidShares.creator, bid.amount) ); uint256 collaboratorShares = 0; Decimal.D256 memory thisCollabsShare; thisCollabsShare.value = 0; // Transfer bid share to the remaining media collaborators for (uint256 i = 0; i < bidShares.collaborators.length; i++) { collaboratorShares = collaboratorShares + (bidShares.collabShares[i]); thisCollabsShare.value = bidShares.collabShares[i]; token.safeTransfer( bidShares.collaborators[i], splitShare(thisCollabsShare, bid.amount) ); } // Transfer bid share to previous owner of media (if applicable) token.safeTransfer( // ZapMedia(mediaContractAddress).getPreviousTokenOwners(tokenId), platformAddress, splitShare(platformFee.fee, bid.amount) ); // Transfer media to bid recipient ZapMedia(mediaContractAddress).auctionTransfer(tokenId, bid.recipient); // Calculate the bid share for the new owner, // equal to 100 - creatorShare - sellOnShare bidShares.owner = Decimal.D256( uint256(100) * (Decimal.BASE) - (collaboratorShares) - (_bidShares[mediaContractAddress][tokenId].creator.value) - (platformFee.fee.value) ); // Set the previous owner share to the accepted bid's sell-on fee // platformFee.fee = bid.sellOnShare; // Remove the accepted bid delete _tokenBidders[mediaContractAddress][tokenId][bidder]; emit BidShareUpdated(tokenId, bidShares, mediaContractAddress); emit BidFinalized(tokenId, bid, mediaContractAddress); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; /** * NOTE: This file is a clone of the dydx protocol's Decimal.sol contract. It was forked from https://github.com/dydxprotocol/solo * at commit 2d8454e02702fe5bc455b848556660629c3cad36 * * It has two modifications: * - it uses a newer solidity in the pragma to match the rest of the contract suite of this project * - it uses BASE_POW to add a level of abstraction for BASE */ import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import {Math} from './Math.sol'; /** * @title Decimal * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE_POW = 18; uint256 constant BASE = 10**BASE_POW; // ============ Structs ============ struct D256 { uint256 value; } // ============ Functions ============ function one() internal pure returns (D256 memory) { return D256({value: BASE}); } function onePlus(D256 memory d) internal pure returns (D256 memory) { return D256({value: d.value.add(BASE)}); } function mul(uint256 target, D256 memory d) internal pure returns (uint256) { return Math.getPartial(target, d.value, BASE); } function div(uint256 target, D256 memory d) internal pure returns (uint256) { return Math.getPartial(target, BASE, d.value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol'; // exposes _registerInterface import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol'; import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import {Math} from '@openzeppelin/contracts/utils/math/Math.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {Counters} from '@openzeppelin/contracts/utils/Counters.sol'; import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; import {IMarket} from './interfaces/IMarket.sol'; import {IMedia} from './interfaces/IMedia.sol'; import {Ownable} from './Ownable.sol'; import {MediaGetter} from './MediaGetter.sol'; import {MediaStorage} from './libraries/MediaStorage.sol'; import './libraries/Constants.sol'; /** * @title A media value system, with perpetual equity to creators * @notice This contract provides an interface to mint media with a market * owned by the creator. */ contract ZapMedia is IMedia, ERC721BurnableUpgradeable, ReentrancyGuardUpgradeable, Ownable, MediaGetter, ERC721URIStorageUpgradeable, ERC721EnumerableUpgradeable, ERC165StorageUpgradeable { using Counters for Counters.Counter; using EnumerableSet for EnumerableSet.UintSet; using SafeMath for uint256; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * DEBUG(need to find the remaining methods that result to the new interfaceId ) * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ mapping(bytes4 => bool) private _supportedInterfaces; bytes internal _contractURI; bytes32 private constant kecEIP712Domain = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); bytes32 private constant kecOne = keccak256(bytes('1')); bytes32 private kecName; /* ********* * Modifiers * ********* */ /** * @notice Require that the token has not been burned and has been minted */ modifier onlyExistingToken(uint256 tokenId) { require( _exists(tokenId), // remove revert string before deployment to mainnet 'Media: nonexistent token' ); _; } /** * @notice Require that the token has had a content hash set */ modifier onlyTokenWithContentHash(uint256 tokenId) { require( getTokenContentHashes(tokenId) != 0, // remove revert string before deployment to mainnet 'Media: token does not have hash of created content' ); _; } /** * @notice Require that the token has had a metadata hash set */ modifier onlyTokenWithMetadataHash(uint256 tokenId) { require( tokens.tokenMetadataHashes[tokenId] != 0, // remove revert string before deployment to mainnet 'Media: token does not have hash of its metadata' ); _; } /** * @notice Ensure that the provided spender is the approved or the owner of * the media for the specified tokenId */ modifier onlyApprovedOrOwner(address spender, uint256 tokenId) { require( _isApprovedOrOwner(spender, tokenId), // remove revert string before deployment to mainnet 'Media: Only approved or owner' ); _; } /** * @notice Ensure the token has been created (even if it has been burned) */ modifier onlyTokenCreated(uint256 tokenId) { require( access._tokenIdTracker.current() > tokenId, // remove revert string before deployment to mainnet 'Media: token with that id does not exist' ); _; } /** * @notice Ensure that the provided URI is not empty */ modifier onlyValidURI(string memory uri) { require( bytes(uri).length != 0, // remove revert string before deployment to mainnet 'Media: specified uri must be non-empty' ); _; } //geting the contractURI value function contractURI() public view returns (bytes memory) { return _contractURI; } /** * @notice On deployment, set the market contract address and register the * ERC721 metadata interface */ function initialize( string calldata name, string calldata symbol, address marketContractAddr, bool permissive, string calldata collectionURI ) external override initializer { __ERC721_init(name, symbol); initialize_ownable(); access.marketContract = marketContractAddr; bytes memory name_b = bytes(name); bytes32 name_b32; assembly { name_b32 := mload(add(name_b, 32)) } kecName = keccak256(name_b); _registerInterface(0x80ac58cd); // registers old erc721 interface for AucitonHouse _registerInterface(0x5b5e139f); // registers current metadata upgradeable interface for AuctionHouse _registerInterface(type(IMedia).interfaceId); access.isPermissive = permissive; _contractURI = bytes(collectionURI); } /** * @notice Returns a boolean, showing whether or not the given interfaceId is supported * @dev This function is overriden from the ERC721 and ERC165 contract stack * @param interfaceId a bytes4 formatted representation of a contract interface * @return boolean dipicting whether or not the interface is supported */ function supportsInterface(bytes4 interfaceId) public view virtual override( ERC721EnumerableUpgradeable, ERC721Upgradeable, ERC165StorageUpgradeable ) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice return the URI for a particular piece of media with the specified tokenId * @dev This function is an override of the base OZ implementation because we * will return the tokenURI even if the media has been burned. In addition, this * protocol does not support a base URI, so relevant conditionals are removed. * @return the URI for a token */ function tokenURI(uint256 tokenId) public view virtual override(ERC721URIStorageUpgradeable, ERC721Upgradeable) onlyTokenCreated(tokenId) returns (string memory) { return ERC721URIStorageUpgradeable.tokenURI(tokenId); } function _registerInterface(bytes4 interfaceId) internal virtual override { require(interfaceId != 0xffffffff, 'ERC165: invalid interface id'); _supportedInterfaces[interfaceId] = true; } /// @notice TokenTransfer hook function /// @dev called from ERC721 Enumerable Upgradeable contract, see here https://docs.openzeppelin.com/contracts/4.x/api/token/erc721#ERC721Enumerable-_beforeTokenTransfer-address-address-uint256- /// @param from the current token owner, if this is the zero address, the token will be minted for `to` /// @param to the receiver's wallet address, if this is the zero address, the token will be burned /// @param tokenId token ID of the ERC721 to be transfered function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721EnumerableUpgradeable, ERC721Upgradeable) { ERC721EnumerableUpgradeable._beforeTokenTransfer(from, to, tokenId); } /* ************* * View Functions * ************** */ /** * @notice Return the metadata URI for a piece of media given the token URI * @param tokenId the token whose metadata will be attached * @return the metadata URI for the token */ function tokenMetadataURI(uint256 tokenId) external view override onlyTokenCreated(tokenId) returns (string memory) { return access._tokenMetadataURIs[tokenId]; } /* **************** * Public Functions * **************** */ /** * @notice see IMedia * @dev mints an NFT and sets the bidshares for collaborators * @param data The media's metadata and content data, includes content and metadata hash, and token's URI */ function mint(MediaData memory data, IMarket.BidShares memory bidShares) public override nonReentrant { require( access.isPermissive || access.approvedToMint[msg.sender] || access.owner == msg.sender, 'Media: Only Approved users can mint' ); require( bidShares.collaborators.length == bidShares.collabShares.length, 'Media: Arrays do not have the same length' ); for (uint256 i = 0; i < bidShares.collaborators.length; i++) { require( _hasShares(i, bidShares), 'Media: Each collaborator must have a share of the nft' ); } _mintForCreator(msg.sender, data, bidShares); } /** * @notice see IMedia */ function mintWithSig( address creator, MediaData memory data, IMarket.BidShares memory bidShares, EIP712Signature memory sig ) public override nonReentrant { require( access.isPermissive || access.approvedToMint[msg.sender], 'Media: Only Approved users can mint' ); require( sig.deadline == 0 || sig.deadline >= block.timestamp, 'Media: mintWithSig expired' ); require( bidShares.collaborators.length == bidShares.collabShares.length, 'Media: Arrays do not have the same length' ); for (uint256 i = 0; i < bidShares.collaborators.length; i++) { require( _hasShares(i, bidShares), 'Media: Each collaborator must have a share of the nft' ); } bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _calculateDomainSeparator(), keccak256( abi.encode( Constants.MINT_WITH_SIG_TYPEHASH, data.contentHash, data.metadataHash, bidShares.creator.value, access.mintWithSigNonces[creator]++, sig.deadline ) ) ) ); address recoveredAddress = ECDSA.recover(digest, sig.v, sig.r, sig.s); require( recoveredAddress != address(0) && creator == recoveredAddress, 'Media: Signature invalid' ); _mintForCreator(recoveredAddress, data, bidShares); } /** * @notice see IMedia */ function auctionTransfer(uint256 tokenId, address recipient) external override { require( msg.sender == access.marketContract, // remove revert string before deployment to mainnet 'Media: only market contract' ); tokens.previousTokenOwners[tokenId] = ownerOf(tokenId); _safeTransfer(ownerOf(tokenId), recipient, tokenId, ''); } /** * @notice see IMedia */ function setAsk(uint256 tokenId, IMarket.Ask memory ask) public override nonReentrant onlyApprovedOrOwner(msg.sender, tokenId) onlyExistingToken(tokenId) { IMarket(access.marketContract).setAsk(tokenId, ask); } /** * @notice see IMedia */ function removeAsk(uint256 tokenId) external override nonReentrant onlyApprovedOrOwner(msg.sender, tokenId) onlyExistingToken(tokenId) { IMarket(access.marketContract).removeAsk(tokenId); } /** * @notice see IMedia */ function setBid(uint256 tokenId, IMarket.Bid memory bid) public override nonReentrant onlyExistingToken(tokenId) { require(msg.sender == bid.bidder, 'Market: Bidder must be msg sender'); IMarket(access.marketContract).setBid(tokenId, bid, msg.sender); } /** * @notice see IMedia */ function removeBid(uint256 tokenId) external override nonReentrant onlyTokenCreated(tokenId) { IMarket(access.marketContract).removeBid(tokenId, msg.sender); } /** * @notice see IMedia */ function acceptBid(uint256 tokenId, IMarket.Bid memory bid) public override nonReentrant onlyApprovedOrOwner(msg.sender, tokenId) onlyExistingToken(tokenId) { IMarket(access.marketContract).acceptBid(address(this), tokenId, bid); } /** * @notice Burn a token. * @dev Only callable if the media owner is also the creator. * @param tokenId the ID of the token to burn */ function burn(uint256 tokenId) public override nonReentrant onlyExistingToken(tokenId) onlyApprovedOrOwner(msg.sender, tokenId) { address owner = ownerOf(tokenId); require( tokens.tokenCreators[tokenId] == owner, // remove revert string before deployment to mainnet 'Media: owner is not creator of media' ); _burn(tokenId); } /** * @notice Revoke the approvals for a token. The provided `approve` function is not sufficient * for this protocol, as it does not allow an approved address to revoke it's own approval. * In instances where a 3rd party is interacting on a user's behalf via `permit`, they should * revoke their approval once their task is complete as a best practice. */ function revokeApproval(uint256 tokenId) external override onlyApprovedOrOwner(msg.sender, tokenId) nonReentrant { _approve(address(0), tokenId); } /** * @notice see IMedia * @dev only callable by approved or owner */ function updateTokenURI(uint256 tokenId, string calldata tokenURILocal) external override nonReentrant onlyApprovedOrOwner(msg.sender, tokenId) onlyTokenWithContentHash(tokenId) onlyValidURI(tokenURILocal) { _setTokenURI(tokenId, tokenURILocal); emit TokenURIUpdated(tokenId, msg.sender, tokenURILocal); } /** * @notice see IMedia * @dev only callable by approved or owner */ function updateTokenMetadataURI( uint256 tokenId, string calldata metadataURI ) external override nonReentrant onlyApprovedOrOwner(msg.sender, tokenId) onlyTokenWithMetadataHash(tokenId) onlyValidURI(metadataURI) { _setTokenMetadataURI(tokenId, metadataURI); emit TokenMetadataURIUpdated(tokenId, msg.sender, metadataURI); } /** * @notice See IMedia * @dev This method is loosely based on the permit for ERC-20 tokens in EIP-2612, but modified * for ERC-721. */ function permit( address spender, uint256 tokenId, EIP712Signature memory sig ) public override nonReentrant onlyExistingToken(tokenId) { require( sig.deadline == 0 || sig.deadline >= block.timestamp, // remove revert string before deployment to mainnet 'Media: Permit expired' ); require( spender != address(0), // remove revert string before deployment to mainnet 'Media: spender cannot be 0x0' ); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _calculateDomainSeparator(), keccak256( abi.encode( Constants.PERMIT_TYPEHASH, spender, tokenId, access.permitNonces[ownerOf(tokenId)][tokenId]++, sig.deadline ) ) ) ); address recoveredAddress = ECDSA.recover(digest, sig.v, sig.r, sig.s); require( recoveredAddress != address(0) && ownerOf(tokenId) == recoveredAddress, // remove revert string before deployment to mainnet 'Media: Signature invalid' ); _approve(spender, tokenId); } /* ***************** * Private Functions * ***************** */ /// @notice Returns a bool depicting whether or not the i'th collaborator has shares /// @dev Explain to a developer any extra details /// @param index the "i'th collaborator" /// @param bidShares the bidshares defined for the Collection's NFTs /// @return Boolean that is true if the i'th collaborator has shares for this collection's NFTs function _hasShares(uint256 index, IMarket.BidShares memory bidShares) internal pure returns (bool) { return (bidShares.collabShares[index] != 0); } /** * @notice Creates a new token for `creator`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_safeMint}. * * On mint, also set the keccak256 hashes of the content and its metadata for integrity * checks, along with the initial URIs to point to the content and metadata. Attribute * the token ID to the creator, mark the content hash as used, and set the bid shares for * the media's market. * * Note that although the content hash must be unique for future mints to prevent duplicate media, * metadata has no such requirement. */ function _mintForCreator( address creator, MediaData memory data, IMarket.BidShares memory bidShares ) internal onlyValidURI(data.tokenURI) onlyValidURI(data.metadataURI) { require(data.contentHash != 0, 'Media: content hash must be non-zero'); require( !access._contentHashes[data.contentHash], 'Media: a token has already been created with this content hash' ); require( data.metadataHash != 0, 'Media: metadata hash must be non-zero' ); uint256 tokenId = access._tokenIdTracker.current(); access._tokenIdTracker.increment(); _safeMint(creator, tokenId); _setTokenContentHash(tokenId, data.contentHash); _setTokenMetadataHash(tokenId, data.metadataHash); _setTokenMetadataURI(tokenId, data.metadataURI); _setTokenURI(tokenId, data.tokenURI); access._creatorTokens[creator].add(tokenId); access._contentHashes[data.contentHash] = true; tokens.tokenCreators[tokenId] = creator; tokens.previousTokenOwners[tokenId] = creator; IMarket(access.marketContract).setBidShares( // address(this), tokenId, bidShares ); IMarket(access.marketContract).mintOrBurn(true, tokenId, address(this)); } function _setTokenContentHash(uint256 tokenId, bytes32 contentHash) internal virtual onlyExistingToken(tokenId) { tokens.tokenContentHashes[tokenId] = contentHash; } function _setTokenMetadataHash(uint256 tokenId, bytes32 metadataHash) internal virtual onlyExistingToken(tokenId) { tokens.tokenMetadataHashes[tokenId] = metadataHash; } function _setTokenMetadataURI(uint256 tokenId, string memory metadataURI) internal virtual onlyExistingToken(tokenId) { access._tokenMetadataURIs[tokenId] = metadataURI; } /** * @notice Destroys `tokenId`. * @dev We modify the OZ _burn implementation to * maintain metadata and to remove the * previous token owner from the piece */ function _burn(uint256 tokenId) internal override(ERC721URIStorageUpgradeable, ERC721Upgradeable) { ERC721URIStorageUpgradeable._burn(tokenId); delete tokens.previousTokenOwners[tokenId]; IMarket(access.marketContract).mintOrBurn( false, tokenId, address(this) ); } /** * @notice transfer a token and remove the ask for it. */ function _transfer( address from, address to, uint256 tokenId ) internal override { IMarket(access.marketContract).removeAsk(tokenId); ERC721Upgradeable._transfer(from, to, tokenId); } /** * @dev Calculates EIP712 DOMAIN_SEPARATOR based on the current contract and chain ID. */ function _calculateDomainSeparator() internal view returns (bytes32) { uint256 chainID; /* solium-disable-next-line */ assembly { chainID := chainid() } return keccak256( abi.encode( kecEIP712Domain, kecName, kecOne, chainID, address(this) ) ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; import {Decimal} from '../Decimal.sol'; /** * @title Interface for Zap NFT Marketplace Protocol's Market */ interface IMarket { struct Bid { // Amount of the currency being bid uint256 amount; // Address to the ERC20 token being used to bid address currency; // Address of the bidder address bidder; // Address of the recipient address recipient; // % of the next sale to award the current owner Decimal.D256 sellOnShare; } struct Ask { // Amount of the currency being asked uint256 amount; // Address to the ERC20 token being asked address currency; } struct BidShares { Decimal.D256 creator; // % of sale value that goes to the seller (current owner) of the nft Decimal.D256 owner; // Array that holds all the collaborators address[] collaborators; // % of sale value that goes to the fourth collaborator of the nft uint256[] collabShares; // Decimal.D256[] collaborators; } struct PlatformFee { // % of sale value that goes to the Vault Decimal.D256 fee; } event BidCreated( address indexed mediaContract, uint256 indexed tokenId, Bid bid ); event BidRemoved( uint256 indexed tokenId, Bid bid, address indexed mediaContract ); event BidFinalized( uint256 indexed tokenId, Bid bid, address indexed mediaContract ); event AskCreated( address indexed mediaContract, uint256 indexed tokenId, Ask ask ); event AskRemoved( uint256 indexed tokenId, Ask ask, address indexed mediaContract ); event BidShareUpdated( uint256 indexed tokenId, BidShares bidShares, address indexed mediaContract ); event MediaContractCreated( address indexed mediaContract, bytes32 name, bytes32 symbol ); event Minted(uint256 indexed token, address indexed mediaContract); event Burned(uint256 indexed token, address indexed mediaContract); function bidForTokenBidder( address mediaContractAddress, uint256 tokenId, address bidder ) external view returns (Bid memory); function currentAskForToken(address mediaContractAddress, uint256 tokenId) external view returns (Ask memory); function bidSharesForToken(address mediaContractAddress, uint256 tokenId) external view returns (BidShares memory); function isValidBid( address mediaContractAddress, uint256 tokenId, uint256 bidAmount ) external view returns (bool); function isValidBidShares(BidShares calldata bidShares) external view returns (bool); function splitShare(Decimal.D256 calldata sharePercentage, uint256 amount) external pure returns (uint256); function isRegistered(address mediaContractAddress) external view returns (bool); function configure( address deployer, address mediaContract, bytes32 name, bytes32 symbol ) external; function revokeRegistration(address mediaContract) external; function registerMedia(address mediaContract) external; function setMediaFactory(address _mediaFactory) external; function mintOrBurn( bool isMint, uint256 tokenId, address mediaContract ) external; function setBidShares(uint256 tokenId, BidShares calldata bidShares) external; function setAsk(uint256 tokenId, Ask calldata ask) external; function removeAsk(uint256 tokenId) external; function setBid( uint256 tokenId, Bid calldata bid, address spender ) external; function removeBid(uint256 tokenId, address bidder) external; function acceptBid( address mediaContractAddress, uint256 tokenId, Bid calldata expectedBid ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol'; contract Ownable is Initializable { event OwnershipTransferInitiated( address indexed owner, address indexed appointedOwner ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); address internal owner; address public appointedOwner; /// @dev The Ownable constructor sets the original `owner` of the contract to the sender account. function initialize() public virtual initializer { owner = msg.sender; } function getOwner() external view returns (address) { return owner; } /// @dev Throws if called by any contract other than latest designated caller modifier onlyOwner() { require( msg.sender == owner, 'Ownable: Only owner has access to this function' ); _; } /// @dev Allows the current owner to intiate the transfer control of the contract to a newOwner. /// @param newOwner The address to transfer ownership to. function initTransferOwnership(address payable newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: Cannot transfer to zero address"); emit OwnershipTransferInitiated(msg.sender, newOwner); appointedOwner = newOwner; } /// @dev Allows new owner to claim the transfer control of the contract function claimTransferOwnership() public { require(appointedOwner != address(0), "Ownable: No ownership transfer have been initiated"); require(msg.sender == appointedOwner, "Ownable: Caller is not the appointed owner of this contract"); emit OwnershipTransferred(owner, msg.sender); owner = appointedOwner; appointedOwner = address(0); } /// @dev Revoke transfer and set appointed owner to 0 address function revokeTransferOwnership() public onlyOwner { appointedOwner = address(0); } } // 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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.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 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: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; /** * @title Math * * Library for non-standard Math functions * NOTE: This file is a clone of the dydx protocol's Math.sol contract. * It was forked from https://github.com/dydxprotocol/solo at commit * 2d8454e02702fe5bc455b848556660629c3cad36. It has two modifications * - uses a newer solidity in the pragma to match the rest of the contract suite of this project. * - Removed `Require.sol` dependency */ library Math { // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target * (numerator / denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return 0 / denominator; } return target * ((numerator - 1) / denominator) + 1; } function to128(uint256 number) internal pure returns (uint128) { require(number<=type(uint128).max, "Math: Unsafe cast to uint128"); uint128 result = uint128(number); return result; } function to96(uint256 number) internal pure returns (uint96) { require(number<=type(uint96).max, "Math: Unsafe cast to uint96"); uint96 result = uint96(number); return result; } function to32(uint256 number) internal pure returns (uint32) { require(number<=type(uint32).max, "Math: Unsafe cast to uint32"); uint32 result = uint32(number); return result; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165StorageUpgradeable is Initializable, ERC165Upgradeable { function __ERC165Storage_init() internal initializer { __ERC165_init_unchained(); __ERC165Storage_init_unchained(); } function __ERC165Storage_init_unchained() internal initializer { } /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721URIStorage_init_unchained(); } function __ERC721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // 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; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; import {IMarket} from './IMarket.sol'; /** * @title Interface for Zap NFT Marketplace Protocol's Media */ interface IMedia { struct EIP712Signature { uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct MediaData { // A valid URI of the content represented by this token string tokenURI; // A valid URI of the metadata associated with this token string metadataURI; // A KECCAK256 hash of the content pointed to by tokenURI bytes32 contentHash; // A KECCAK256 hash of the content pointed to by metadataURI bytes32 metadataHash; } event TokenURIUpdated(uint256 indexed _tokenId, address owner, string _uri); event TokenMetadataURIUpdated( uint256 indexed _tokenId, address owner, string _uri ); function initialize( string memory name, string memory symbol, address marketContractAddr, bool permissive, string memory collectionMetadata ) external; /** * @notice Return the metadata URI for a piece of media given the token URI */ function tokenMetadataURI(uint256 tokenId) external view returns (string memory); /** * @notice Mint new media for msg.sender. */ function mint(MediaData calldata data, IMarket.BidShares calldata bidShares) external; /** * @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature. */ function mintWithSig( address creator, MediaData calldata data, IMarket.BidShares calldata bidShares, EIP712Signature calldata sig ) external; /** * @notice Transfer the token with the given ID to a given address. * Save the previous owner before the transfer, in case there is a sell-on fee. * @dev This can only be called by the auction contract specified at deployment */ function auctionTransfer(uint256 tokenId, address recipient) external; /** * @notice Set the ask on a piece of media */ function setAsk(uint256 tokenId, IMarket.Ask calldata ask) external; /** * @notice Remove the ask on a piece of media */ function removeAsk(uint256 tokenId) external; /** * @notice Set the bid on a piece of media */ function setBid(uint256 tokenId, IMarket.Bid calldata bid) external; /** * @notice Remove the bid on a piece of media */ function removeBid(uint256 tokenId) external; function acceptBid(uint256 tokenId, IMarket.Bid calldata bid) external; /** * @notice Revoke approval for a piece of media */ function revokeApproval(uint256 tokenId) external; /** * @notice Update the token URI */ function updateTokenURI(uint256 tokenId, string calldata tokenURI) external; /** * @notice Update the token metadata uri */ function updateTokenMetadataURI( uint256 tokenId, string calldata metadataURI ) external; /** * @notice EIP-712 permit method. Sets an approved spender given a valid signature. */ function permit( address spender, uint256 tokenId, EIP712Signature calldata sig ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import {MediaStorage} from "./libraries/MediaStorage.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract Ownable is Initializable { event OwnershipTransferInitiated( address indexed owner, address indexed appointedOwner ); event OwnershipTransferred(address indexed previousOwner,address indexed newOwner); MediaStorage.Access internal access; address public appointedOwner; /// @dev The Ownable constructor sets the original `access.owner` of the contract to the sender account. function initialize_ownable() internal initializer { access.owner = msg.sender; } function getOwner() external view returns (address) { return access.owner; } /// @dev Throws if called by any contract other than latest designated caller modifier onlyOwner() { require(msg.sender == access.owner, "onlyOwner error: Only Owner of the Contract can make this Call"); _; } function approveToMint(address toApprove) external onlyOwner { access.approvedToMint[toApprove] = true; } function getTokenMetadataURIs(uint256 _tokenId) external view returns (string memory metadataUri) { return access._tokenMetadataURIs[_tokenId]; } function getSigNonces(address _minter) public view returns (uint256 nonce) { return access.mintWithSigNonces[_minter]; } function getPermitNonce(address _user, uint256 _tokenId) public view returns (uint256 nonce){ return access.permitNonces[_user][_tokenId]; } function marketContract() public view returns (address) { return access.marketContract; } /// @dev Allows the current owner to intiate the transfer control of the contract to a newOwner. /// @param newOwner The address to transfer ownership to. function initTransferOwnership(address payable newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: Cannot transfer to zero address"); emit OwnershipTransferInitiated(access.owner, newOwner); appointedOwner = newOwner; } /// @dev Allows new owner to claim the transfer control of the contract function claimTransferOwnership() public { require(appointedOwner != address(0), "Ownable: No ownership transfer have been initiated"); require(msg.sender == appointedOwner, "Ownable: Caller is not the appointed owner of this contract"); emit OwnershipTransferred(access.owner, msg.sender); // where msg.sender == appointedOwner access.owner = appointedOwner; appointedOwner = address(0); } /// @dev Revoke transfer and set appointed owner to 0 address function revokeTransferOwnership() public onlyOwner { appointedOwner = address(0); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import {MediaGettersLib} from './libraries/MediaGettersLib.sol'; import {MediaStorage} from './libraries/MediaStorage.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; /// @title A title that should describe the contract/interface /// @author The name of the author /// @notice Explain to an end user what this does /// @dev Explain to a developer any extra details contract MediaGetter is Initializable { using MediaGettersLib for MediaStorage.Tokens; MediaStorage.Tokens internal tokens; function getTokenCreators(uint256 _tokenId) public view returns (address creator) { creator = tokens.getTokenCreators(_tokenId); } function getPreviousTokenOwners(uint256 _tokenId) public view returns (address prevOwner) { prevOwner = tokens.getPreviousTokenOwners(_tokenId); } function getTokenContentHashes(uint256 _tokenId) public view returns (bytes32 contentHash) { contentHash = tokens.getTokenContentHashes(_tokenId); } function getTokenMetadataHashes(uint256 _tokenId) public view returns (bytes32 metadataHash) { metadataHash = tokens.getTokenMetadataHashes(_tokenId); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import {Counters} from '@openzeppelin/contracts/utils/Counters.sol'; import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; /// @title A title that should describe the contract/interface /// @author The name of the author /// @notice Explain to an end user what this does /// @dev Explain to a developer any extra details library MediaStorage { using EnumerableSet for EnumerableSet.UintSet; using Counters for Counters.Counter; /* ******* * Globals * ******* */ struct Tokens { // Mapping from token to previous owner of the token mapping(uint256 => address) previousTokenOwners; // Mapping from token id to creator address mapping(uint256 => address) tokenCreators; // Mapping from token id to keccak256 hash of content mapping(uint256 => bytes32) tokenContentHashes; // Mapping from token id to keccak256 hash of metadata mapping(uint256 => bytes32) tokenMetadataHashes; } struct Access { // Address for the market address marketContract; address owner; // Mapping from Media address to whether or not to allow permissive minting bool isPermissive; // Mapping from creator address to their (enumerable) set of created tokens mapping(address => EnumerableSet.UintSet) _creatorTokens; // Mapping from contentHash to bool mapping(bytes32 => bool) _contentHashes; // Mapping from address to token id to permit nonce mapping(address => mapping(uint256 => uint256)) permitNonces; // Mapping from address to mint with sig nonce mapping(address => uint256) mintWithSigNonces; // Mapping from address to boolean; can this address mint? mapping(address => bool) approvedToMint; // Mapping from token id to metadataURI mapping(uint256 => string) _tokenMetadataURIs; Counters.Counter _tokenIdTracker; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; library Constants{ //keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH =keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"); //keccak256("MintWithSig(bytes32 contentHash,bytes32 metadataHash,uint256 creatorShare,uint256 nonce,uint256 deadline)"); bytes32 public constant MINT_WITH_SIG_TYPEHASH =keccak256("MintWithSig(bytes32 contentHash,bytes32 metadataHash,uint256 creatorShare,uint256 nonce,uint256 deadline)"); bytes4 internal constant _INTERFACE_ID_ERC721_METADATA = 0x4e222e66; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import {MediaStorage} from "./MediaStorage.sol"; library MediaGettersLib { function getTokenCreators(MediaStorage.Tokens storage self, uint256 _tokenId) internal view returns (address creator) { return self.tokenCreators[_tokenId]; } function getPreviousTokenOwners(MediaStorage.Tokens storage self, uint256 _tokenId) internal view returns (address prevOwner) { return self.previousTokenOwners[_tokenId]; } function getTokenContentHashes(MediaStorage.Tokens storage self, uint256 _tokenId) internal view returns (bytes32 contentHash) { return self.tokenContentHashes[_tokenId]; } function getTokenMetadataHashes(MediaStorage.Tokens storage self, uint256 _tokenId) internal view returns (bytes32 metadataHash) { return self.tokenMetadataHashes[_tokenId]; } }
see IMedia/
function setBid(uint256 tokenId, IMarket.Bid memory bid) public override nonReentrant onlyExistingToken(tokenId) { require(msg.sender == bid.bidder, 'Market: Bidder must be msg sender'); IMarket(access.marketContract).setBid(tokenId, bid, msg.sender); }
6,322,121
/** *Submitted for verification at Etherscan.io on 2020-09-18 */ /** *Submitted for verification at Etherscan.io on 2020-09-18 */ // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/token/ERC20/IERC20.sol pragma solidity 0.5.7; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/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: nexusmutual-contracts/contracts/external/openzeppelin-solidity/math/SafeMath.sol pragma solidity 0.5.7; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { //require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; //require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: nexusmutual-contracts/contracts/NXMToken.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract NXMToken is IERC20 { using SafeMath for uint256; event WhiteListed(address indexed member); event BlackListed(address indexed member); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public whiteListed; mapping(address => uint) public isLockedForMV; uint256 private _totalSupply; string public name = "NXM"; string public symbol = "NXM"; uint8 public decimals = 18; address public operator; modifier canTransfer(address _to) { require(whiteListed[_to]); _; } modifier onlyOperator() { if (operator != address(0)) require(msg.sender == operator); _; } constructor(address _founderAddress, uint _initialSupply) public { _mint(_founderAddress, _initialSupply); } /** * @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 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 Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Adds a user to whitelist * @param _member address to add to whitelist */ function addToWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = true; emit WhiteListed(_member); return true; } /** * @dev removes a user from whitelist * @param _member address to remove from whitelist */ function removeFromWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = false; emit BlackListed(_member); return true; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public returns (bool) { _burn(msg.sender, amount); return true; } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public returns (bool) { _burnFrom(from, value); return true; } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator { _mint(account, amount); } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public canTransfer(to) returns (bool) { require(isLockedForMV[msg.sender] < now); // if not voted under governance require(value <= _balances[msg.sender]); _transfer(to, value); return true; } /** * @dev Transfer tokens to the operator from the specified address * @param from The address to transfer from. * @param value The amount to be transferred. */ function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) { require(value <= _balances[from]); _transferFrom(from, operator, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public canTransfer(to) returns (bool) { require(isLockedForMV[from] < now); // if not voted under governance require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyOperator { if (_days.add(now) > isLockedForMV[_of]) isLockedForMV[_of] = _days.add(now); } /** * @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) internal { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } /** * @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 ) internal { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IProposalCategory { event Category( uint indexed categoryId, string categoryName, string actionHash ); /// @dev Adds new category /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external; /// @dev gets category details function category(uint _categoryId) external view returns( uint categoryId, uint memberRoleToVote, uint majorityVotePerc, uint quorumPerc, uint[] memory allowedToCreateProposal, uint closingTime, uint minStake ); ///@dev gets category action details function categoryAction(uint _categoryId) external view returns( uint categoryId, address contractAddress, bytes2 contractName, uint defaultIncentive ); /// @dev Gets Total number of categories added till now function totalCategories() external view returns(uint numberOfCategories); /// @dev Updates category details /// @param _categoryId Category id that needs to be updated /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public; } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/Governed.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMaster { function getLatestAddress(bytes2 _module) public view returns(address); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns(bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } // File: nexusmutual-contracts/contracts/INXMMaster.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract INXMMaster { address public tokenAddress; address public owner; uint public pauseTime; function delegateCallBack(bytes32 myid) external; function masterInitialized() public view returns(bool); function isInternal(address _add) public view returns(bool); function isPause() public view returns(bool check); function isOwner(address _add) public view returns(bool); function isMember(address _add) public view returns(bool); function checkIsAuthToGoverned(address _add) public view returns(bool); function updatePauseTime(uint _time) public; function dAppLocker() public view returns(address _add); function dAppToken() public view returns(address _add); function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress); } // File: nexusmutual-contracts/contracts/Iupgradable.sol pragma solidity 0.5.7; contract Iupgradable { INXMMaster public ms; address public nxMasterAddress; modifier onlyInternal { require(ms.isInternal(msg.sender)); _; } modifier isMemberAndcheckPause { require(ms.isPause() == false && ms.isMember(msg.sender) == true); _; } modifier onlyOwner { require(ms.isOwner(msg.sender)); _; } modifier checkPause { require(ms.isPause() == false); _; } modifier isMember { require(ms.isMember(msg.sender), "Not member"); _; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public; /** * @dev change master address * @param _masterAddress is the new address */ function changeMasterAddress(address _masterAddress) public { if (address(ms) != address(0)) { require(address(ms) == msg.sender, "Not master"); } ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } } // File: nexusmutual-contracts/contracts/interfaces/IPooledStaking.sol pragma solidity ^0.5.7; interface IPooledStaking { function accumulateReward(address contractAddress, uint amount) external; function pushBurn(address contractAddress, uint amount) external; function hasPendingActions() external view returns (bool); function contractStake(address contractAddress) external view returns (uint); function stakerReward(address staker) external view returns (uint); function stakerDeposit(address staker) external view returns (uint); function stakerContractStake(address staker, address contractAddress) external view returns (uint); function withdraw(uint amount) external; function stakerMaxWithdrawable(address stakerAddress) external view returns (uint); function withdrawReward(address stakerAddress) external; } // File: nexusmutual-contracts/contracts/TokenFunctions.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenFunctions is Iupgradable { using SafeMath for uint; MCR internal m1; MemberRoles internal mr; NXMToken public tk; TokenController internal tc; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; PoolData internal pd; IPooledStaking pooledStaking; event BurnCATokens(uint claimId, address addr, uint amount); /** * @dev Rewards stakers on purchase of cover on smart contract. * @param _contractAddress smart contract address. * @param _coverPriceNXM cover price in NXM. */ function pushStakerRewards(address _contractAddress, uint _coverPriceNXM) external onlyInternal { uint rewardValue = _coverPriceNXM.mul(td.stakerCommissionPer()).div(100); pooledStaking.accumulateReward(_contractAddress, rewardValue); } /** * @dev Deprecated in favor of burnStakedTokens */ function burnStakerLockedToken(uint, bytes4, uint) external { // noop } /** * @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed. * @param coverId cover id * @param coverCurrency cover currency * @param sumAssured amount of $curr to burn */ function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal { (, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = m1.calculateTokenPrice(coverCurrency); uint burnNXMAmount = sumAssured.mul(1e18).div(tokenPrice); pooledStaking.pushBurn(scAddress, burnNXMAmount); } /** * @dev Gets the total staked NXM tokens against * Smart contract by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function deprecated_getTotalStakedTokensOnSmartContract( address _stakedContractAddress ) external view returns(uint) { uint stakedAmount = 0; address stakerAddress; uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress); for (uint i = 0; i < staketLen; i++) { stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i); uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress, _stakedContractAddress, stakerIndex); stakedAmount = stakedAmount.add(currentlyStaked); } return stakedAmount; } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) { return _getUserLockedCNTokens(_of, _coverId); } /** * @dev to get the all the cover locked tokens of a user * @param _of is the user address in concern * @return amount locked */ function getUserAllLockedCNTokens(address _of) external view returns(uint amount) { for (uint i = 0; i < qd.getUserCoverLength(_of); i++) { amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i])); } } /** * @dev Returns amount of NXM Tokens locked as Cover Note against given coverId. * @param _coverId coverId of the cover. */ function getLockedCNAgainstCover(uint _coverId) external view returns(uint) { return _getLockedCNAgainstCover(_coverId); } /** * @dev Returns total amount of staked NXM Tokens on all smart contracts. * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) { uint stakedAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i); stakedAmount = stakedAmount.add(currentlyStaked); } amount = stakedAmount; } /** * @dev Returns total unlockable amount of staked NXM Tokens on all smart contract . * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllUnlockableStakedTokens( address _stakerAddress ) external view returns (uint amount) { uint unlockableAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = unlockableAmount.add( _deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress, scIndex)); } amount = unlockableAmount; } /** * @dev Change Dependent Contract Address */ function changeDependentContractAddress() public { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); gv = Governance(ms.getLatestAddress("GV")); mr = MemberRoles(ms.getLatestAddress("MR")); pd = PoolData(ms.getLatestAddress("PD")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /** * @dev Gets the Token price in a given currency * @param curr Currency name. * @return price Token Price. */ function getTokenPrice(bytes4 curr) public view returns(uint price) { price = m1.calculateTokenPrice(curr); } /** * @dev Set the flag to check if cover note is deposited against the cover id * @param coverId Cover Id. */ function depositCN(uint coverId) public onlyInternal returns (bool success) { require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available"); td.setDepositCN(coverId, true); success = true; } /** * @param _of address of Member * @param _coverId Cover Id * @param _lockTime Pending Time + Cover Period 7*1 days */ function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal { uint timeStamp = now.add(_lockTime); uint coverValidUntil = qd.getValidityOfCover(_coverId); if (timeStamp >= coverValidUntil) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); tc.extendLockOf(_of, reason, timeStamp); } } /** * @dev to burn the deposited cover tokens * @param coverId is id of cover whose tokens have to be burned * @return the status of the successful burning */ function burnDepositCN(uint coverId) public onlyInternal returns (bool success) { address _of = qd.getCoverMemberAddress(coverId); uint amount; (amount, ) = td.depositedCN(coverId); amount = (amount.mul(50)).div(100); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); tc.burnLockedTokens(_of, reason, amount); success = true; } /** * @dev Unlocks covernote locked against a given cover * @param coverId id of cover */ function unlockCN(uint coverId) public onlyInternal { (, bool isDeposited) = td.depositedCN(coverId); require(!isDeposited,"Cover note is deposited and can not be released"); uint lockedCN = _getLockedCNAgainstCover(coverId); if (lockedCN != 0) { address coverHolder = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId)); tc.releaseLockedTokens(coverHolder, reason, lockedCN); } } /** * @dev Burns tokens used for fraudulent voting against a claim * @param claimid Claim Id. * @param _value number of tokens to be burned * @param _of Claim Assessor's address. */ function burnCAToken(uint claimid, uint _value, address _of) public { require(ms.checkIsAuthToGoverned(msg.sender)); tc.burnLockedTokens(_of, "CLA", _value); emit BurnCATokens(claimid, _of, _value); } /** * @dev to lock cover note tokens * @param coverNoteAmount is number of tokens to be locked * @param coverPeriod is cover period in concern * @param coverId is the cover id of cover in concern * @param _of address whose tokens are to be locked */ function lockCN( uint coverNoteAmount, uint coverPeriod, uint coverId, address _of ) public onlyInternal { uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp()); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); td.setDepositCNAmount(coverId, coverNoteAmount); tc.lockOf(_of, reason, coverNoteAmount, validity); } /** * @dev to check if a member is locked for member vote * @param _of is the member address in concern * @return the boolean status */ function isLockedForMemberVote(address _of) public view returns(bool) { return now < tk.isLockedForMV(_of); } /** * @dev Internal function to gets amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress, _stakedContractAddress, _stakedContractIndex); } /** * @dev Function to gets unlockable amount of locked NXM * tokens, staked against smartcontract by index * @param stakerAddress address of staker * @param stakedContractAddress staked contract address * @param stakerIndex index of staking */ function deprecated_getStakerUnlockableTokensOnSmartContract ( address stakerAddress, address stakedContractAddress, uint stakerIndex ) public view returns (uint) { return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress, td.getStakerStakedContractIndex(stakerAddress, stakerIndex)); } /** * @dev releases unlockable staked tokens to staker */ function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause { uint unlockableAmount; address scAddress; bytes32 reason; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract( _stakerAddress, scAddress, scIndex); td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0); td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount); reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex)); tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount); } } /** * @dev to get tokens of staker locked before burning that are allowed to burn * @param stakerAdd is the address of the staker * @param stakedAdd is the address of staked contract in concern * @param stakerIndex is the staker index in concern * @return amount of unlockable tokens * @return amount of tokens that can burn */ function _deprecated_unlockableBeforeBurningAndCanBurn( address stakerAdd, address stakedAdd, uint stakerIndex ) public view returns (uint amount, uint canBurn) { uint dateAdd; uint initialStake; uint totalBurnt; uint ub; (, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex); canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays()); // Can't use SafeMaths for int. int v = int(initialStake - (canBurn) - (totalBurnt) - ( td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub)); uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract( stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex)); if (v < 0) { v = 0; } amount = uint(v); if (canBurn > currentLockedTokens.sub(amount).sub(ub)) { canBurn = currentLockedTokens.sub(amount).sub(ub); } } /** * @dev to get tokens of staker that are unlockable * @param _stakerAddress is the address of the staker * @param _stakedContractAddress is the address of staked contract in concern * @param _stakedContractIndex is the staked contract index in concern * @return amount of unlockable tokens */ function _deprecated_getStakerUnlockableTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { uint initialStake; uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); uint burnt; (, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex); uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex); uint currentStakedTokens; (, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, _stakedContractAddress, stakerIndex); amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt); } /** * @dev Internal function to get the amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function _deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) internal view returns (uint amount) { bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); amount = tc.tokensLocked(_stakerAddress, reason); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _coverId coverId of the cover. */ function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) { address coverHolder = qd.getCoverMemberAddress(_coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId)); return tc.tokensLockedAtTime(coverHolder, reason, now); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); return tc.tokensLockedAtTime(_of, reason, now); } /** * @dev Internal function to gets remaining amount of staked NXM tokens, * against smartcontract by index * @param _stakeAmount address of user * @param _stakeDays staked contract address * @param _validDays index of staking */ function _deprecated_calculateStakedTokens( uint _stakeAmount, uint _stakeDays, uint _validDays ) internal pure returns (uint amount) { if (_validDays > _stakeDays) { uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays); amount = (rf.mul(_stakeAmount)).div(100000); } else { amount = 0; } } /** * @dev Gets the total staked NXM tokens against Smart contract * by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function _deprecated_burnStakerTokenLockedAgainstSmartContract( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _amount ) internal { uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount); bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); tc.burnLockedTokens(_stakerAddress, reason, _amount); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMemberRoles { event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription); /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole(bytes32 _roleName, string memory _roleDescription, address _authorized) public; /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole(address _memberAddress, uint _roleId, bool _active) public; /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _authorized New authorized address against role id function changeAuthorized(uint _roleId, address _authorized) public; /// @dev Return number of member roles function totalRoles() public view returns(uint256); /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory allMemberAddress); /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberAddress.length Member length function numberOfMembers(uint _memberRoleId) public view returns(uint); /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address); /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory assignedRoles); /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool); } // File: nexusmutual-contracts/contracts/external/ERC1132/IERC1132.sol pragma solidity 0.5.7; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract IERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } // File: nexusmutual-contracts/contracts/TokenController.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenController is IERC1132, Iupgradable { using SafeMath for uint256; event Burned(address indexed member, bytes32 lockedUnder, uint256 amount); NXMToken public token; IPooledStaking public pooledStaking; uint public minCALockTime = uint(30).mul(1 days); bytes32 private constant CLA = bytes32("CLA"); /** * @dev Just for interface */ function changeDependentContractAddress() public { token = NXMToken(ms.tokenAddress()); pooledStaking = IPooledStaking(ms.getLatestAddress('PS')); } /** * @dev to change the operator address * @param _newOperator is the new address of operator */ function changeOperator(address _newOperator) public onlyInternal { token.changeOperator(_newOperator); } /** * @dev Proxies token transfer through this contract to allow staking when members are locked for voting * @param _from Source address * @param _to Destination address * @param _value Amount to transfer */ function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) { require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address"); require(token.operatorTransfer(_from, _value), "Operator transfer failed"); require(token.transfer(_to, _value), "Internal transfer failed"); return true; } /** * @dev Locks a specified amount of tokens, * for CLA reason and for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(minCALockTime <= _time,"Should lock for minimum time"); // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(msg.sender, _reason, _amount, _time); return true; } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address whose tokens are to be locked */ function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) public onlyInternal returns (bool) { // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(_of, _reason, _amount, _time); return true; } /** * @dev Extends lock for reason CLA for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); _extendLock(msg.sender, _reason, _time); return true; } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLockOf(address _of, bytes32 _reason, uint256 _time) public onlyInternal returns (bool) { _extendLock(_of, _reason, _time); return true; } /** * @dev Increase number of tokens locked for a CLA reason * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(_tokensLocked(msg.sender, _reason) > 0); token.operatorTransfer(msg.sender, _amount); locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity); return true; } /** * @dev burns tokens of an address * @param _of is the address to burn tokens of * @param amount is the amount to burn * @return the boolean status of the burning process */ function burnFrom (address _of, uint amount) public onlyInternal returns (bool) { return token.burnFrom(_of, amount); } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _burnLockedTokens(_of, _reason, _amount); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal { _reduceLock(_of, _reason, _time); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _releaseLockedTokens(_of, _reason, _amount); } /** * @dev Adds an address to whitelist maintained in the contract * @param _member address to add to whitelist */ function addToWhitelist(address _member) public onlyInternal { token.addToWhiteList(_member); } /** * @dev Removes an address from the whitelist in the token * @param _member address to remove */ function removeFromWhitelist(address _member) public onlyInternal { token.removeFromWhiteList(_member); } /** * @dev Mints new token for an address * @param _member address to reward the minted tokens * @param _amount number of tokens to mint */ function mint(address _member, uint _amount) public onlyInternal { token.mint(_member, _amount); } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyInternal { token.lockForMemberVote(_of, _days); } /** * @dev Unlocks the unlockable tokens against CLA of a specified address * @param _of Address of user, claiming back unlockable tokens against CLA */ function unlock(address _of) public checkPause returns (uint256 unlockableTokens) { unlockableTokens = _tokensUnlockable(_of, CLA); if (unlockableTokens > 0) { locked[_of][CLA].claimed = true; emit Unlocked(_of, CLA, unlockableTokens); require(token.transfer(_of, unlockableTokens)); } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MNCLT") { minCALockTime = val.mul(1 days); } else { revert("Invalid param code"); } } /** * @dev Gets the validity of locked tokens of a specified address * @param _of The address to query the validity * @param reason reason for which tokens were locked */ function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) { validity = locked[_of][reason].validity; } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensLocked(_of, _reason); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensUnlockable(_of, _reason); } function totalSupply() public view returns (uint256) { return token.totalSupply(); } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { return _tokensLockedAtTime(_of, _reason, _time); } /** * @dev Returns the total amount of tokens held by an address: * transferable + locked + staked for pooled staking - pending burns. * Used by Claims and Governance in member voting to calculate the user's vote weight. * * @param _of The address to query the total balance of * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount) { amount = token.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } uint stakerReward = pooledStaking.stakerReward(_of); uint stakerDeposit = pooledStaking.stakerDeposit(_of); amount = amount.add(stakerDeposit).add(stakerReward); } /** * @dev Returns the total locked tokens at time * Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility * for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment. * Does not take into account pending burns. * * @param _of member whose locked tokens are to be calculate * @param _time timestamp when the tokens should be locked */ function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) { for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time)); } amount = amount.add(pooledStaking.stakerDeposit(_of)); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal { require(_tokensLocked(_of, _reason) == 0); require(_amount != 0); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } require(token.operatorTransfer(_of, _amount)); uint256 validUntil = now.add(_time); //solhint-disable-line locked[_of][_reason] = LockToken(_amount, validUntil, false); emit Locked(_of, _reason, _amount, validUntil); } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function _tokensLocked(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (!locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) internal view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) { amount = locked[_of][_reason].amount; } } /** * @dev Extends lock for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function _extendLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } token.burn(_amount); emit Burned(_of, _reason, _amount); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } require(token.transfer(_of, _amount)); emit Unlocked(_of, _reason, _amount); } function _removeReason(address _of, bytes32 _reason) internal { uint len = lockReason[_of].length; for (uint i = 0; i < len; i++) { if (lockReason[_of][i] == _reason) { lockReason[_of][i] = lockReason[_of][len.sub(1)]; lockReason[_of].pop(); break; } } } } // File: nexusmutual-contracts/contracts/ClaimsData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns(uint voteCount) { return allvotes.length.sub(1); //Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns(uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns(address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns(uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns(uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns(address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns(uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns(uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns(uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns(uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns(uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns(uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns(uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns(int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns(uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns(uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); //0 Pending-Claim Assessor Vote _pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); //12 Claim Accepted Payout Pending _pushStatus(0, 0); //13 Claim Accepted No Payout _pushStatus(0, 0); //14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } // File: nexusmutual-contracts/contracts/PoolData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract DSValue { function peek() public view returns (bytes32, bool); function read() public view returns (bytes32); } contract PoolData is Iupgradable { using SafeMath for uint; struct ApiId { bytes4 typeOf; bytes4 currency; uint id; uint64 dateAdd; uint64 dateUpd; } struct CurrencyAssets { address currAddress; uint baseMin; uint varMin; } struct InvestmentAssets { address currAddress; bool status; uint64 minHoldingPercX100; uint64 maxHoldingPercX100; uint8 decimals; } struct IARankDetails { bytes4 maxIACurr; uint64 maxRate; bytes4 minIACurr; uint64 minRate; } struct McrData { uint mcrPercx100; uint mcrEther; uint vFull; //Pool funds uint64 date; } IARankDetails[] internal allIARankDetails; McrData[] public allMCRData; bytes4[] internal allInvestmentCurrencies; bytes4[] internal allCurrencies; bytes32[] public allAPIcall; mapping(bytes32 => ApiId) public allAPIid; mapping(uint64 => uint) internal datewiseId; mapping(bytes16 => uint) internal currencyLastIndex; mapping(bytes4 => CurrencyAssets) internal allCurrencyAssets; mapping(bytes4 => InvestmentAssets) internal allInvestmentAssets; mapping(bytes4 => uint) internal caAvgRate; mapping(bytes4 => uint) internal iaAvgRate; address public notariseMCR; address public daiFeedAddress; uint private constant DECIMAL1E18 = uint(10) ** 18; uint public uniswapDeadline; uint public liquidityTradeCallbackTime; uint public lastLiquidityTradeTrigger; uint64 internal lastDate; uint public variationPercX100; uint public iaRatesTime; uint public minCap; uint public mcrTime; uint public a; uint public shockParameter; uint public c; uint public mcrFailTime; uint public ethVolumeLimit; uint public capReached; uint public capacityLimit; constructor(address _notariseAdd, address _daiFeedAdd, address _daiAdd) public { notariseMCR = _notariseAdd; daiFeedAddress = _daiFeedAdd; c = 5800000; a = 1028; mcrTime = 24 hours; mcrFailTime = 6 hours; allMCRData.push(McrData(0, 0, 0, 0)); minCap = 12000 * DECIMAL1E18; shockParameter = 50; variationPercX100 = 100; //1% iaRatesTime = 24 hours; //24 hours in seconds uniswapDeadline = 20 minutes; liquidityTradeCallbackTime = 4 hours; ethVolumeLimit = 4; capacityLimit = 10; allCurrencies.push("ETH"); allCurrencyAssets["ETH"] = CurrencyAssets(address(0), 1000 * DECIMAL1E18, 0); allCurrencies.push("DAI"); allCurrencyAssets["DAI"] = CurrencyAssets(_daiAdd, 50000 * DECIMAL1E18, 0); allInvestmentCurrencies.push("ETH"); allInvestmentAssets["ETH"] = InvestmentAssets(address(0), true, 2500, 10000, 18); allInvestmentCurrencies.push("DAI"); allInvestmentAssets["DAI"] = InvestmentAssets(_daiAdd, true, 250, 1500, 18); } /** * @dev to set the maximum cap allowed * @param val is the new value */ function setCapReached(uint val) external onlyInternal { capReached = val; } /// @dev Updates the 3 day average rate of a IA currency. /// To be replaced by MakerDao's on chain rates /// @param curr IA Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateIAAvgRate(bytes4 curr, uint rate) external onlyInternal { iaAvgRate[curr] = rate; } /// @dev Updates the 3 day average rate of a CA currency. /// To be replaced by MakerDao's on chain rates /// @param curr Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateCAAvgRate(bytes4 curr, uint rate) external onlyInternal { caAvgRate[curr] = rate; } /// @dev Adds details of (Minimum Capital Requirement)MCR. /// @param mcrp Minimum Capital Requirement percentage (MCR% * 100 ,Ex:for 54.56% ,given 5456) /// @param vf Pool fund value in Ether used in the last full daily calculation from the Capital model. function pushMCRData(uint mcrp, uint mcre, uint vf, uint64 time) external onlyInternal { allMCRData.push(McrData(mcrp, mcre, vf, time)); } /** * @dev Updates the Timestamp at which result of oracalize call is received. */ function updateDateUpdOfAPI(bytes32 myid) external onlyInternal { allAPIid[myid].dateUpd = uint64(now); } /** * @dev Saves the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal,quote,cover etc. for which oraclize call is made */ function saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) external onlyInternal { allAPIid[myid] = ApiId(_typeof, "", id, uint64(now), uint64(now)); } /** * @dev Stores the id return by the oraclize query. * Maintains record of all the Ids return by oraclize query. * @param myid Id return by the oraclize query. */ function addInAllApiCall(bytes32 myid) external onlyInternal { allAPIcall.push(myid); } /** * @dev Saves investment asset rank details. * @param maxIACurr Maximum ranked investment asset currency. * @param maxRate Maximum ranked investment asset rate. * @param minIACurr Minimum ranked investment asset currency. * @param minRate Minimum ranked investment asset rate. * @param date in yyyymmdd. */ function saveIARankDetails( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate, uint64 date ) external onlyInternal { allIARankDetails.push(IARankDetails(maxIACurr, maxRate, minIACurr, minRate)); datewiseId[date] = allIARankDetails.length.sub(1); } /** * @dev to get the time for the laste liquidity trade trigger */ function setLastLiquidityTradeTrigger() external onlyInternal { lastLiquidityTradeTrigger = now; } /** * @dev Updates Last Date. */ function updatelastDate(uint64 newDate) external onlyInternal { lastDate = newDate; } /** * @dev Adds currency asset currency. * @param curr currency of the asset * @param currAddress address of the currency * @param baseMin base minimum in 10^18. */ function addCurrencyAssetCurrency( bytes4 curr, address currAddress, uint baseMin ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencies.push(curr); allCurrencyAssets[curr] = CurrencyAssets(currAddress, baseMin, 0); } /** * @dev Adds investment asset. */ function addInvestmentAssetCurrency( bytes4 curr, address currAddress, bool status, uint64 minHoldingPercX100, uint64 maxHoldingPercX100, uint8 decimals ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentCurrencies.push(curr); allInvestmentAssets[curr] = InvestmentAssets(currAddress, status, minHoldingPercX100, maxHoldingPercX100, decimals); } /** * @dev Changes base minimum of a given currency asset. */ function changeCurrencyAssetBaseMin(bytes4 curr, uint baseMin) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].baseMin = baseMin; } /** * @dev changes variable minimum of a given currency asset. */ function changeCurrencyAssetVarMin(bytes4 curr, uint varMin) external onlyInternal { allCurrencyAssets[curr].varMin = varMin; } /** * @dev Changes the investment asset status. */ function changeInvestmentAssetStatus(bytes4 curr, bool status) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].status = status; } /** * @dev Changes the investment asset Holding percentage of a given currency. */ function changeInvestmentAssetHoldingPerc( bytes4 curr, uint64 minPercX100, uint64 maxPercX100 ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].minHoldingPercX100 = minPercX100; allInvestmentAssets[curr].maxHoldingPercX100 = maxPercX100; } /** * @dev Gets Currency asset token address. */ function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].currAddress = currAdd; } /** * @dev Changes Investment asset token address. */ function changeInvestmentAssetAddressAndDecimal( bytes4 curr, address currAdd, uint8 newDecimal ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].currAddress = currAdd; allInvestmentAssets[curr].decimals = newDecimal; } /// @dev Changes address allowed to post MCR. function changeNotariseAddress(address _add) external onlyInternal { notariseMCR = _add; } /// @dev updates daiFeedAddress address. /// @param _add address of DAI feed. function changeDAIfeedAddress(address _add) external onlyInternal { daiFeedAddress = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "MCRTIM") { val = mcrTime / (1 hours); } else if (code == "MCRFTIM") { val = mcrFailTime / (1 hours); } else if (code == "MCRMIN") { val = minCap; } else if (code == "MCRSHOCK") { val = shockParameter; } else if (code == "MCRCAPL") { val = capacityLimit; } else if (code == "IMZ") { val = variationPercX100; } else if (code == "IMRATET") { val = iaRatesTime / (1 hours); } else if (code == "IMUNIDL") { val = uniswapDeadline / (1 minutes); } else if (code == "IMLIQT") { val = liquidityTradeCallbackTime / (1 hours); } else if (code == "IMETHVL") { val = ethVolumeLimit; } else if (code == "C") { val = c; } else if (code == "A") { val = a; } } /// @dev Checks whether a given address can notaise MCR data or not. /// @param _add Address. /// @return res Returns 0 if address is not authorized, else 1. function isnotarise(address _add) external view returns(bool res) { res = false; if (_add == notariseMCR) res = true; } /// @dev Gets the details of last added MCR. /// @return mcrPercx100 Total Minimum Capital Requirement percentage of that month of year(multiplied by 100). /// @return vFull Total Pool fund value in Ether used in the last full daily calculation. function getLastMCR() external view returns(uint mcrPercx100, uint mcrEtherx1E18, uint vFull, uint64 date) { uint index = allMCRData.length.sub(1); return ( allMCRData[index].mcrPercx100, allMCRData[index].mcrEther, allMCRData[index].vFull, allMCRData[index].date ); } /// @dev Gets last Minimum Capital Requirement percentage of Capital Model /// @return val MCR% value,multiplied by 100. function getLastMCRPerc() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrPercx100; } /// @dev Gets last Ether price of Capital Model /// @return val ether value,multiplied by 100. function getLastMCREther() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrEther; } /// @dev Gets Pool fund value in Ether used in the last full daily calculation from the Capital model. function getLastVfull() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].vFull; } /// @dev Gets last Minimum Capital Requirement in Ether. /// @return date of MCR. function getLastMCRDate() external view returns(uint64 date) { date = allMCRData[allMCRData.length.sub(1)].date; } /// @dev Gets details for token price calculation. function getTokenPriceDetails(bytes4 curr) external view returns(uint _a, uint _c, uint rate) { _a = a; _c = c; rate = _getAvgRate(curr, false); } /// @dev Gets the total number of times MCR calculation has been made. function getMCRDataLength() external view returns(uint len) { len = allMCRData.length; } /** * @dev Gets investment asset rank details by given date. */ function getIARankDetailsByDate( uint64 date ) external view returns( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate ) { uint index = datewiseId[date]; return ( allIARankDetails[index].maxIACurr, allIARankDetails[index].maxRate, allIARankDetails[index].minIACurr, allIARankDetails[index].minRate ); } /** * @dev Gets Last Date. */ function getLastDate() external view returns(uint64 date) { return lastDate; } /** * @dev Gets investment currency for a given index. */ function getInvestmentCurrencyByIndex(uint index) external view returns(bytes4 currName) { return allInvestmentCurrencies[index]; } /** * @dev Gets count of investment currency. */ function getInvestmentCurrencyLen() external view returns(uint len) { return allInvestmentCurrencies.length; } /** * @dev Gets all the investment currencies. */ function getAllInvestmentCurrencies() external view returns(bytes4[] memory currencies) { return allInvestmentCurrencies; } /** * @dev Gets All currency for a given index. */ function getCurrenciesByIndex(uint index) external view returns(bytes4 currName) { return allCurrencies[index]; } /** * @dev Gets count of All currency. */ function getAllCurrenciesLen() external view returns(uint len) { return allCurrencies.length; } /** * @dev Gets all currencies */ function getAllCurrencies() external view returns(bytes4[] memory currencies) { return allCurrencies; } /** * @dev Gets currency asset details for a given currency. */ function getCurrencyAssetVarBase( bytes4 curr ) external view returns( bytes4 currency, uint baseMin, uint varMin ) { return ( curr, allCurrencyAssets[curr].baseMin, allCurrencyAssets[curr].varMin ); } /** * @dev Gets minimum variable value for currency asset. */ function getCurrencyAssetVarMin(bytes4 curr) external view returns(uint varMin) { return allCurrencyAssets[curr].varMin; } /** * @dev Gets base minimum of a given currency asset. */ function getCurrencyAssetBaseMin(bytes4 curr) external view returns(uint baseMin) { return allCurrencyAssets[curr].baseMin; } /** * @dev Gets investment asset maximum and minimum holding percentage of a given currency. */ function getInvestmentAssetHoldingPerc( bytes4 curr ) external view returns( uint64 minHoldingPercX100, uint64 maxHoldingPercX100 ) { return ( allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100 ); } /** * @dev Gets investment asset decimals. */ function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) { return allInvestmentAssets[curr].decimals; } /** * @dev Gets investment asset maximum holding percentage of a given currency. */ function getInvestmentAssetMaxHoldingPerc(bytes4 curr) external view returns(uint64 maxHoldingPercX100) { return allInvestmentAssets[curr].maxHoldingPercX100; } /** * @dev Gets investment asset minimum holding percentage of a given currency. */ function getInvestmentAssetMinHoldingPerc(bytes4 curr) external view returns(uint64 minHoldingPercX100) { return allInvestmentAssets[curr].minHoldingPercX100; } /** * @dev Gets investment asset details of a given currency */ function getInvestmentAssetDetails( bytes4 curr ) external view returns( bytes4 currency, address currAddress, bool status, uint64 minHoldingPerc, uint64 maxHoldingPerc, uint8 decimals ) { return ( curr, allInvestmentAssets[curr].currAddress, allInvestmentAssets[curr].status, allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100, allInvestmentAssets[curr].decimals ); } /** * @dev Gets Currency asset token address. */ function getCurrencyAssetAddress(bytes4 curr) external view returns(address) { return allCurrencyAssets[curr].currAddress; } /** * @dev Gets investment asset token address. */ function getInvestmentAssetAddress(bytes4 curr) external view returns(address) { return allInvestmentAssets[curr].currAddress; } /** * @dev Gets investment asset active Status of a given currency. */ function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) { return allInvestmentAssets[curr].status; } /** * @dev Gets type of oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return _typeof It could be of type "quote","quotation","cover","claim" etc. */ function getApiIdTypeOf(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].typeOf; } /** * @dev Gets ID associated to oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return id1 It could be the ID of "proposal","quotation","cover","claim" etc. */ function getIdOfApiId(bytes32 myid) external view returns(uint) { return allAPIid[myid].id; } /** * @dev Gets the Timestamp of a oracalize call. */ function getDateAddOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateAdd; } /** * @dev Gets the Timestamp at which result of oracalize call is received. */ function getDateUpdOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateUpd; } /** * @dev Gets currency by oracalize id. */ function getCurrOfApiId(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].currency; } /** * @dev Gets ID return by the oraclize query of a given index. * @param index Index. * @return myid ID return by the oraclize query. */ function getApiCallIndex(uint index) external view returns(bytes32 myid) { myid = allAPIcall[index]; } /** * @dev Gets Length of API call. */ function getApilCallLength() external view returns(uint) { return allAPIcall.length; } /** * @dev Get Details of Oraclize API when given Oraclize Id. * @param myid ID return by the oraclize query. * @return _typeof ype of the query for which oraclize * call is made.("proposal","quote","quotation" etc.) */ function getApiCallDetails( bytes32 myid ) external view returns( bytes4 _typeof, bytes4 curr, uint id, uint64 dateAdd, uint64 dateUpd ) { return ( allAPIid[myid].typeOf, allAPIid[myid].currency, allAPIid[myid].id, allAPIid[myid].dateAdd, allAPIid[myid].dateUpd ); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MCRTIM") { _changeMCRTime(val * 1 hours); } else if (code == "MCRFTIM") { _changeMCRFailTime(val * 1 hours); } else if (code == "MCRMIN") { _changeMinCap(val); } else if (code == "MCRSHOCK") { _changeShockParameter(val); } else if (code == "MCRCAPL") { _changeCapacityLimit(val); } else if (code == "IMZ") { _changeVariationPercX100(val); } else if (code == "IMRATET") { _changeIARatesTime(val * 1 hours); } else if (code == "IMUNIDL") { _changeUniswapDeadlineTime(val * 1 minutes); } else if (code == "IMLIQT") { _changeliquidityTradeCallbackTime(val * 1 hours); } else if (code == "IMETHVL") { _setEthVolumeLimit(val); } else if (code == "C") { _changeC(val); } else if (code == "A") { _changeA(val); } else { revert("Invalid param code"); } } /** * @dev to get the average rate of currency rate * @param curr is the currency in concern * @return required rate */ function getCAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, false); } /** * @dev to get the average rate of investment rate * @param curr is the investment in concern * @return required rate */ function getIAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, true); } function changeDependentContractAddress() public onlyInternal {} /// @dev Gets the average rate of a CA currency. /// @param curr Currency Name. /// @return rate Average rate X 100(of last 3 days). function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) { if (curr == "DAI") { DSValue ds = DSValue(daiFeedAddress); rate = uint(ds.read()).div(uint(10) ** 16); } else if (isIA) { rate = iaAvgRate[curr]; } else { rate = caAvgRate[curr]; } } /** * @dev to set the ethereum volume limit * @param val is the new limit value */ function _setEthVolumeLimit(uint val) internal { ethVolumeLimit = val; } /// @dev Sets minimum Cap. function _changeMinCap(uint newCap) internal { minCap = newCap; } /// @dev Sets Shock Parameter. function _changeShockParameter(uint newParam) internal { shockParameter = newParam; } /// @dev Changes time period for obtaining new MCR data from external oracle query. function _changeMCRTime(uint _time) internal { mcrTime = _time; } /// @dev Sets MCR Fail time. function _changeMCRFailTime(uint _time) internal { mcrFailTime = _time; } /** * @dev to change the uniswap deadline time * @param newDeadline is the value */ function _changeUniswapDeadlineTime(uint newDeadline) internal { uniswapDeadline = newDeadline; } /** * @dev to change the liquidity trade call back time * @param newTime is the new value to be set */ function _changeliquidityTradeCallbackTime(uint newTime) internal { liquidityTradeCallbackTime = newTime; } /** * @dev Changes time after which investment asset rates need to be fed. */ function _changeIARatesTime(uint _newTime) internal { iaRatesTime = _newTime; } /** * @dev Changes the variation range percentage. */ function _changeVariationPercX100(uint newPercX100) internal { variationPercX100 = newPercX100; } /// @dev Changes Growth Step function _changeC(uint newC) internal { c = newC; } /// @dev Changes scaling factor. function _changeA(uint val) internal { a = val; } /** * @dev to change the capacity limit * @param val is the new value */ function _changeCapacityLimit(uint val) internal { capacityLimit = val; } } // File: nexusmutual-contracts/contracts/QuotationData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract QuotationData is Iupgradable { using SafeMath for uint; enum HCIDStatus { NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover } enum CoverStatus { Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested } struct Cover { address payable memberAddress; bytes4 currencyCode; uint sumAssured; uint16 coverPeriod; uint validUntil; address scAddress; uint premiumNXM; } struct HoldCover { uint holdCoverId; address payable userAddress; address scAddress; bytes4 coverCurr; uint[] coverDetails; uint16 coverPeriod; } address public authQuoteEngine; mapping(bytes4 => uint) internal currencyCSA; mapping(address => uint[]) internal userCover; mapping(address => uint[]) public userHoldedCover; mapping(address => bool) public refundEligible; mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd; mapping(uint => uint8) public coverStatus; mapping(uint => uint) public holdedCoverIDStatus; mapping(uint => bool) public timestampRepeated; Cover[] internal allCovers; HoldCover[] internal allCoverHolded; uint public stlp; uint public stl; uint public pm; uint public minDays; uint public tokensRetained; address public kycAuthAddress; event CoverDetailsEvent( uint indexed cid, address scAdd, uint sumAssured, uint expiry, uint premium, uint premiumNXM, bytes4 curr ); event CoverStatusEvent(uint indexed cid, uint8 statusNum); constructor(address _authQuoteAdd, address _kycAuthAdd) public { authQuoteEngine = _authQuoteAdd; kycAuthAddress = _kycAuthAdd; stlp = 90; stl = 100; pm = 30; minDays = 30; tokensRetained = 10; allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0)); uint[] memory arr = new uint[](1); allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0)); } /// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be added. function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be subtracted. function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be subtracted. function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Adds the amount in Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be added. function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev sets bit for timestamp to avoid replay attacks. function setTimestampRepeated(uint _timestamp) external onlyInternal { timestampRepeated[_timestamp] = true; } /// @dev Creates a blank new cover. function addCover( uint16 _coverPeriod, uint _sumAssured, address payable _userAddress, bytes4 _currencyCode, address _scAddress, uint premium, uint premiumNXM ) external onlyInternal { uint expiryDate = now.add(uint(_coverPeriod).mul(1 days)); allCovers.push(Cover(_userAddress, _currencyCode, _sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM)); uint cid = allCovers.length.sub(1); userCover[_userAddress].push(cid); emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode); } /// @dev create holded cover which will process after verdict of KYC. function addHoldCover( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod ) external onlyInternal { uint holdedCoverLen = allCoverHolded.length; holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending); allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress, coverCurr, coverDetails, coverPeriod)); userHoldedCover[from].push(allCoverHolded.length.sub(1)); } ///@dev sets refund eligible bit. ///@param _add user address. ///@param status indicates if user have pending kyc. function setRefundEligible(address _add, bool status) external onlyInternal { refundEligible[_add] = status; } /// @dev to set current status of particular holded coverID (1 for not completed KYC, /// 2 for KYC passed, 3 for failed KYC or full refunded, /// 4 for KYC completed but cover not processed) function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal { holdedCoverIDStatus[holdedCoverID] = status; } /** * @dev to set address of kyc authentication * @param _add is the new address */ function setKycAuthAddress(address _add) external onlyInternal { kycAuthAddress = _add; } /// @dev Changes authorised address for generating quote off chain. function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "STLP") { val = stlp; } else if (code == "STL") { val = stl; } else if (code == "PM") { val = pm; } else if (code == "QUOMIND") { val = minDays; } else if (code == "QUOTOK") { val = tokensRetained; } } /// @dev Gets Product details. /// @return _minDays minimum cover period. /// @return _PM Profit margin. /// @return _STL short term Load. /// @return _STLP short term load period. function getProductDetails() external view returns ( uint _minDays, uint _pm, uint _stl, uint _stlp ) { _minDays = minDays; _pm = pm; _stl = stl; _stlp = stlp; } /// @dev Gets total number covers created till date. function getCoverLength() external view returns(uint len) { return (allCovers.length); } /// @dev Gets Authorised Engine address. function getAuthQuoteEngine() external view returns(address _add) { _add = authQuoteEngine; } /// @dev Gets the Total Sum Assured amount of a given currency. function getTotalSumAssured(bytes4 _curr) external view returns(uint amount) { amount = currencyCSA[_curr]; } /// @dev Gets all the Cover ids generated by a given address. /// @param _add User's address. /// @return allCover array of covers. function getAllCoversOfUser(address _add) external view returns(uint[] memory allCover) { return (userCover[_add]); } /// @dev Gets total number of covers generated by a given address function getUserCoverLength(address _add) external view returns(uint len) { len = userCover[_add].length; } /// @dev Gets the status of a given cover. function getCoverStatusNo(uint _cid) external view returns(uint8) { return coverStatus[_cid]; } /// @dev Gets the Cover Period (in days) of a given cover. function getCoverPeriod(uint _cid) external view returns(uint32 cp) { cp = allCovers[_cid].coverPeriod; } /// @dev Gets the Sum Assured Amount of a given cover. function getCoverSumAssured(uint _cid) external view returns(uint sa) { sa = allCovers[_cid].sumAssured; } /// @dev Gets the Currency Name in which a given cover is assured. function getCurrencyOfCover(uint _cid) external view returns(bytes4 curr) { curr = allCovers[_cid].currencyCode; } /// @dev Gets the validity date (timestamp) of a given cover. function getValidityOfCover(uint _cid) external view returns(uint date) { date = allCovers[_cid].validUntil; } /// @dev Gets Smart contract address of cover. function getscAddressOfCover(uint _cid) external view returns(uint, address) { return (_cid, allCovers[_cid].scAddress); } /// @dev Gets the owner address of a given cover. function getCoverMemberAddress(uint _cid) external view returns(address payable _add) { _add = allCovers[_cid].memberAddress; } /// @dev Gets the premium amount of a given cover in NXM. function getCoverPremiumNXM(uint _cid) external view returns(uint _premiumNXM) { _premiumNXM = allCovers[_cid].premiumNXM; } /// @dev Provides the details of a cover Id /// @param _cid cover Id /// @return memberAddress cover user address. /// @return scAddress smart contract Address /// @return currencyCode currency of cover /// @return sumAssured sum assured of cover /// @return premiumNXM premium in NXM function getCoverDetailsByCoverID1( uint _cid ) external view returns ( uint cid, address _memberAddress, address _scAddress, bytes4 _currencyCode, uint _sumAssured, uint premiumNXM ) { return ( _cid, allCovers[_cid].memberAddress, allCovers[_cid].scAddress, allCovers[_cid].currencyCode, allCovers[_cid].sumAssured, allCovers[_cid].premiumNXM ); } /// @dev Provides details of a cover Id /// @param _cid cover Id /// @return status status of cover. /// @return sumAssured Sum assurance of cover. /// @return coverPeriod Cover Period of cover (in days). /// @return validUntil is validity of cover. function getCoverDetailsByCoverID2( uint _cid ) external view returns ( uint cid, uint8 status, uint sumAssured, uint16 coverPeriod, uint validUntil ) { return ( _cid, coverStatus[_cid], allCovers[_cid].sumAssured, allCovers[_cid].coverPeriod, allCovers[_cid].validUntil ); } /// @dev Provides details of a holded cover Id /// @param _hcid holded cover Id /// @return scAddress SmartCover address of cover. /// @return coverCurr currency of cover. /// @return coverPeriod Cover Period of cover (in days). function getHoldedCoverDetailsByID1( uint _hcid ) external view returns ( uint hcid, address scAddress, bytes4 coverCurr, uint16 coverPeriod ) { return ( _hcid, allCoverHolded[_hcid].scAddress, allCoverHolded[_hcid].coverCurr, allCoverHolded[_hcid].coverPeriod ); } /// @dev Gets total number holded covers created till date. function getUserHoldedCoverLength(address _add) external view returns (uint) { return userHoldedCover[_add].length; } /// @dev Gets holded cover index by index of user holded covers. function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) { return userHoldedCover[_add][index]; } /// @dev Provides the details of a holded cover Id /// @param _hcid holded cover Id /// @return memberAddress holded cover user address. /// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute. function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails ) { return ( _hcid, allCoverHolded[_hcid].userAddress, allCoverHolded[_hcid].coverDetails ); } /// @dev Gets the Total Sum Assured amount of a given currency and smart contract address. function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns(uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; } //solhint-disable-next-line function changeDependentContractAddress() public {} /// @dev Changes the status of a given cover. /// @param _cid cover Id. /// @param _stat New status. function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal { coverStatus[_cid] = _stat; emit CoverStatusEvent(_cid, _stat); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "STLP") { _changeSTLP(val); } else if (code == "STL") { _changeSTL(val); } else if (code == "PM") { _changePM(val); } else if (code == "QUOMIND") { _changeMinDays(val); } else if (code == "QUOTOK") { _setTokensRetained(val); } else { revert("Invalid param code"); } } /// @dev Changes the existing Profit Margin value function _changePM(uint _pm) internal { pm = _pm; } /// @dev Changes the existing Short Term Load Period (STLP) value. function _changeSTLP(uint _stlp) internal { stlp = _stlp; } /// @dev Changes the existing Short Term Load (STL) value. function _changeSTL(uint _stl) internal { stl = _stl; } /// @dev Changes the existing Minimum cover period (in days) function _changeMinDays(uint _days) internal { minDays = _days; } /** * @dev to set the the amount of tokens retained * @param val is the amount retained */ function _setTokensRetained(uint val) internal { tokensRetained = val; } } // File: nexusmutual-contracts/contracts/TokenData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenData is Iupgradable { using SafeMath for uint; address payable public walletAddress; uint public lockTokenTimeAfterCoverExp; uint public bookTime; uint public lockCADays; uint public lockMVDays; uint public scValidDays; uint public joiningFee; uint public stakerCommissionPer; uint public stakerMaxCommissionPer; uint public tokenExponent; uint public priceStep; struct StakeCommission { uint commissionEarned; uint commissionRedeemed; } struct Stake { address stakedContractAddress; uint stakedContractIndex; uint dateAdd; uint stakeAmount; uint unlockedAmount; uint burnedAmount; uint unLockableBeforeLastBurn; } struct Staker { address stakerAddress; uint stakerIndex; } struct CoverNote { uint amount; bool isDeposited; } /** * @dev mapping of uw address to array of sc address to fetch * all staked contract address of underwriter, pushing * data into this array of Stake returns stakerIndex */ mapping(address => Stake[]) public stakerStakedContracts; /** * @dev mapping of sc address to array of UW address to fetch * all underwritters of the staked smart contract * pushing data into this mapped array returns scIndex */ mapping(address => Staker[]) public stakedContractStakers; /** * @dev mapping of staked contract Address to the array of StakeCommission * here index of this array is stakedContractIndex */ mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission; mapping(address => uint) public lastCompletedStakeCommission; /** * @dev mapping of the staked contract address to the current * staker index who will receive commission. */ mapping(address => uint) public stakedContractCurrentCommissionIndex; /** * @dev mapping of the staked contract address to the * current staker index to burn token from. */ mapping(address => uint) public stakedContractCurrentBurnIndex; /** * @dev mapping to return true if Cover Note deposited against coverId */ mapping(uint => CoverNote) public depositedCN; mapping(address => uint) internal isBookedTokens; event Commission( address indexed stakedContractAddress, address indexed stakerAddress, uint indexed scIndex, uint commissionAmount ); constructor(address payable _walletAdd) public { walletAddress = _walletAdd; bookTime = 12 hours; joiningFee = 2000000000000000; // 0.002 Ether lockTokenTimeAfterCoverExp = 35 days; scValidDays = 250; lockCADays = 7 days; lockMVDays = 2 days; stakerCommissionPer = 20; stakerMaxCommissionPer = 50; tokenExponent = 4; priceStep = 1000; } /** * @dev Change the wallet address which receive Joining Fee */ function changeWalletAddress(address payable _address) external onlyInternal { walletAddress = _address; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "TOKEXP") { val = tokenExponent; } else if (code == "TOKSTEP") { val = priceStep; } else if (code == "RALOCKT") { val = scValidDays; } else if (code == "RACOMM") { val = stakerCommissionPer; } else if (code == "RAMAXC") { val = stakerMaxCommissionPer; } else if (code == "CABOOKT") { val = bookTime / (1 hours); } else if (code == "CALOCKT") { val = lockCADays / (1 days); } else if (code == "MVLOCKT") { val = lockMVDays / (1 days); } else if (code == "QUOLOCKT") { val = lockTokenTimeAfterCoverExp / (1 days); } else if (code == "JOINFEE") { val = joiningFee; } } /** * @dev Just for interface */ function changeDependentContractAddress() public { //solhint-disable-line } /** * @dev to get the contract staked by a staker * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return the address of staked contract */ function getStakerStakedContractByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (address stakedContractAddress) { stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; } /** * @dev to get the staker's staked burned * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount burned */ function getStakerStakedBurnedByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint burnedAmount) { burnedAmount = stakerStakedContracts[ _stakerAddress][_stakerIndex].burnedAmount; } /** * @dev to get the staker's staked unlockable before the last burn * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return unlockable staked tokens */ function getStakerStakedUnlockableBeforeLastBurnByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint unlockable) { unlockable = stakerStakedContracts[ _stakerAddress][_stakerIndex].unLockableBeforeLastBurn; } /** * @dev to get the staker's staked contract index * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return is the index of the smart contract address */ function getStakerStakedContractIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint scIndex) { scIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; } /** * @dev to get the staker index of the staked contract * @param _stakedContractAddress is the address of the staked contract * @param _stakedContractIndex is the index of staked contract * @return is the index of the staker */ function getStakedContractStakerIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint sIndex) { sIndex = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerIndex; } /** * @dev to get the staker's initial staked amount on the contract * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return staked amount */ function getStakerInitialStakedAmountOnContract( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakeAmount; } /** * @dev to get the staker's staked contract length * @param _stakerAddress is the address of the staker * @return length of staked contract */ function getStakerStakedContractLength( address _stakerAddress ) public view returns (uint length) { length = stakerStakedContracts[_stakerAddress].length; } /** * @dev to get the staker's unlocked tokens which were staked * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount */ function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].unlockedAmount; } /** * @dev pushes the unlocked staked tokens by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the Burned tokens for a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be burned. */ function pushBurnedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function pushUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev sets the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function setUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = _amount; } /** * @dev pushes the earned commission earned by a staker. * @param _stakerAddress address of staker. * @param _stakedContractAddress address of smart contract. * @param _stakedContractIndex index of the staker to distribute commission. * @param _commissionAmount amount to be given as commission. */ function pushEarnedStakeCommissions( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _commissionAmount ) public onlyInternal { stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex]. commissionEarned = stakedContractStakeCommission[_stakedContractAddress][ _stakedContractIndex].commissionEarned.add(_commissionAmount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Commission( _stakerAddress, _stakedContractAddress, _stakedContractIndex, _commissionAmount ); } /** * @dev pushes the redeemed commission redeemed by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushRedeemedStakeCommissions( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { uint stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; address stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; stakedContractStakeCommission[stakedContractAddress][stakedContractIndex]. commissionRedeemed = stakedContractStakeCommission[ stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Gets stake commission given to an underwriter * for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets stake commission redeemed by an underwriter * for particular staked contract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. * @return commissionEarned total amount given to staker. */ function getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalEarnedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionEarned) { totalCommissionEarned = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionEarned = totalCommissionEarned. add(_getStakerEarnedStakeCommission(_stakerAddress, i)); } } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalReedmedStakeCommission( address _stakerAddress ) public view returns(uint totalCommissionRedeemed) { totalCommissionRedeemed = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionRedeemed = totalCommissionRedeemed.add( _getStakerRedeemedStakeCommission(_stakerAddress, i)); } } /** * @dev set flag to deposit/ undeposit cover note * against a cover Id * @param coverId coverId of Cover * @param flag true/false for deposit/undeposit */ function setDepositCN(uint coverId, bool flag) public onlyInternal { if (flag == true) { require(!depositedCN[coverId].isDeposited, "Cover note already deposited"); } depositedCN[coverId].isDeposited = flag; } /** * @dev set locked cover note amount * against a cover Id * @param coverId coverId of Cover * @param amount amount of nxm to be locked */ function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; } /** * @dev to get the staker address on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @param _stakedContractIndex is the index of staked contract's index * @return address of staker */ function getStakedContractStakerByIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (address stakerAddress) { stakerAddress = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerAddress; } /** * @dev to get the length of stakers on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @return length in concern */ function getStakedContractStakersLength( address _stakedContractAddress ) public view returns (uint length) { length = stakedContractStakers[_stakedContractAddress].length; } /** * @dev Adds a new stake record. * @param _stakerAddress staker address. * @param _stakedContractAddress smart contract address. * @param _amount amountof NXM to be staked. */ function addStake( address _stakerAddress, address _stakedContractAddress, uint _amount ) public onlyInternal returns(uint scIndex) { scIndex = (stakedContractStakers[_stakedContractAddress].push( Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1); stakerStakedContracts[_stakerAddress].push( Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0)); } /** * @dev books the user's tokens for maintaining Assessor Velocity, * i.e. once a token is used to cast a vote as a Claims assessor, * @param _of user's address. */ function bookCATokens(address _of) public onlyInternal { require(!isCATokensBooked(_of), "Tokens already booked"); isBookedTokens[_of] = now.add(bookTime); } /** * @dev to know if claim assessor's tokens are booked or not * @param _of is the claim assessor's address in concern * @return boolean representing the status of tokens booked */ function isCATokensBooked(address _of) public view returns(bool res) { if (now < isBookedTokens[_of]) res = true; } /** * @dev Sets the index which will receive commission. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentCommissionIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index; } /** * @dev Sets the last complete commission index * @param _stakerAddress smart contract address. * @param _index current index. */ function setLastCompletedStakeCommissionIndex( address _stakerAddress, uint _index ) public onlyInternal { lastCompletedStakeCommission[_stakerAddress] = _index; } /** * @dev Sets the index till which commission is distrubuted. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentBurnIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentBurnIndex[_stakedContractAddress] = _index; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "TOKEXP") { _setTokenExponent(val); } else if (code == "TOKSTEP") { _setPriceStep(val); } else if (code == "RALOCKT") { _changeSCValidDays(val); } else if (code == "RACOMM") { _setStakerCommissionPer(val); } else if (code == "RAMAXC") { _setStakerMaxCommissionPer(val); } else if (code == "CABOOKT") { _changeBookTime(val * 1 hours); } else if (code == "CALOCKT") { _changelockCADays(val * 1 days); } else if (code == "MVLOCKT") { _changelockMVDays(val * 1 days); } else if (code == "QUOLOCKT") { _setLockTokenTimeAfterCoverExp(val * 1 days); } else if (code == "JOINFEE") { _setJoiningFee(val); } else { revert("Invalid param code"); } } /** * @dev Internal function to get stake commission given to an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionEarned; } /** * @dev Internal function to get stake commission redeemed by an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionRedeemed; } /** * @dev to set the percentage of staker commission * @param _val is new percentage value */ function _setStakerCommissionPer(uint _val) internal { stakerCommissionPer = _val; } /** * @dev to set the max percentage of staker commission * @param _val is new percentage value */ function _setStakerMaxCommissionPer(uint _val) internal { stakerMaxCommissionPer = _val; } /** * @dev to set the token exponent value * @param _val is new value */ function _setTokenExponent(uint _val) internal { tokenExponent = _val; } /** * @dev to set the price step * @param _val is new value */ function _setPriceStep(uint _val) internal { priceStep = _val; } /** * @dev Changes number of days for which NXM needs to staked in case of underwriting */ function _changeSCValidDays(uint _days) internal { scValidDays = _days; } /** * @dev Changes the time period up to which tokens will be locked. * Used to generate the validity period of tokens booked by * a user for participating in claim's assessment/claim's voting. */ function _changeBookTime(uint _time) internal { bookTime = _time; } /** * @dev Changes lock CA days - number of days for which tokens * are locked while submitting a vote. */ function _changelockCADays(uint _val) internal { lockCADays = _val; } /** * @dev Changes lock MV days - number of days for which tokens are locked * while submitting a vote. */ function _changelockMVDays(uint _val) internal { lockMVDays = _val; } /** * @dev Changes extra lock period for a cover, post its expiry. */ function _setLockTokenTimeAfterCoverExp(uint time) internal { lockTokenTimeAfterCoverExp = time; } /** * @dev Set the joining fee for membership */ function _setJoiningFee(uint _amount) internal { joiningFee = _amount; } } // File: nexusmutual-contracts/contracts/external/oraclize/ethereum-api/usingOraclize.sol /* ORACLIZE_API Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity >= 0.5.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI! // Dummy contract only used to emit to end-user they are using wrong solc contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external; } contract OraclizeI { address public cbAddress; function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function getPrice(string memory _datasource) public returns (uint _dsprice); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice); function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id); function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id); function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id); } contract OraclizeAddrResolverI { function getAddress() public returns (address _address); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, 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. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory _buf, uint _capacity) internal pure { uint capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint _a, uint _b) private pure returns (uint _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt(Buffer.buffer memory _buf, int _value) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value)); } } function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { using CBOR for Buffer.buffer; OraclizeI oraclize; OraclizeAddrResolverI OAR; 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_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string oraclize_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; modifier oraclizeAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { oraclize_setNetwork(networkID_auto); } if (address(oraclize) != OAR.getAddress()) { oraclize = OraclizeI(OAR.getAddress()); } _; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) { // RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) { return oraclize_setNetwork(); _networkID; // silence the warning and remain backwards compatible } function oraclize_setNetworkName(string memory _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string memory _networkName) { return oraclize_network_name; } function oraclize_setNetwork() internal returns (bool _networkSet) { 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(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41); oraclize_setNetworkName("eth_goerli"); 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 memory _result) public { __callback(_myid, _result, new bytes(0)); } function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public { return; _myid; _result; _proof; // Silence compiler warnings } function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource); } function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit); } function oraclize_query(string memory _datasource, string memory _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 memory _datasource, string memory _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 memory _datasource, string memory _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 memory _datasource, string memory _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 memory _datasource, string memory _arg1, string memory _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 memory _datasource, string memory _arg1, string memory _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 memory _datasource, string memory _arg1, string memory _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 memory _datasource, string memory _arg1, string memory _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 memory _datasource, string[] memory _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 memory _datasource, string[] memory _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 memory _datasource, string[] memory _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 memory _datasource, string[] memory _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 memory _datasource, string[1] memory _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 memory _datasource, string[1] memory _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 memory _datasource, string[1] memory _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 memory _datasource, string[1] memory _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 memory _datasource, string[2] memory _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 memory _datasource, string[2] memory _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 memory _datasource, string[2] memory _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 memory _datasource, string[2] memory _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 memory _datasource, string[3] memory _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 memory _datasource, string[3] memory _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 memory _datasource, string[3] memory _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 memory _datasource, string[3] memory _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 memory _datasource, string[4] memory _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 memory _datasource, string[4] memory _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 memory _datasource, string[4] memory _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 memory _datasource, string[4] memory _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 memory _datasource, string[5] memory _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 memory _datasource, string[5] memory _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 memory _datasource, string[5] memory _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 memory _datasource, string[5] memory _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 memory _datasource, bytes[] memory _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 memory _datasource, bytes[] memory _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 memory _datasource, bytes[] memory _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 memory _datasource, bytes[] memory _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 memory _datasource, bytes[1] memory _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 memory _datasource, bytes[1] memory _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 memory _datasource, bytes[1] memory _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 memory _datasource, bytes[1] memory _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 memory _datasource, bytes[2] memory _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 memory _datasource, bytes[2] memory _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 memory _datasource, bytes[2] memory _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 memory _datasource, bytes[2] memory _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 memory _datasource, bytes[3] memory _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 memory _datasource, bytes[3] memory _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 memory _datasource, bytes[3] memory _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 memory _datasource, bytes[3] memory _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 memory _datasource, bytes[4] memory _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 memory _datasource, bytes[4] memory _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 memory _datasource, bytes[4] memory _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 memory _datasource, bytes[4] memory _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 memory _datasource, bytes[5] memory _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 memory _datasource, bytes[5] memory _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 memory _datasource, bytes[5] memory _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 memory _datasource, bytes[5] memory _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_setProof(byte _proofP) oraclizeAPI internal { return oraclize.setProofType(_proofP); } function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) { return oraclize.cbAddress(); } function getCodeSize(address _addr) view internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(_gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) { return oraclize.randomDS_getSessionPubKeyHash(); } function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { 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(uint8(tmp[i])); b2 = uint160(uint8(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 memory _a, string memory _b) internal pure returns (int _returnCode) { 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 memory _haystack, string memory _needle) internal pure returns (int _returnCode) { 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 memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { 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; uint i = 0; for (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 safeParseInt(string memory _a) internal pure returns (uint _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { require(!decimals, 'More than one decimal encountered in string!'); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } 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); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /* The following variables can be relaxed. Check the relaxed random contract at https://github.com/oraclize/ethereum-examples for an idea on how to override and replace commit hash variables. */ mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal { oraclize_randomDS_args[_queryId] = _commitment; } function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(_dersig, offset + (uint(uint8(_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(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) { bool sigok; // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(uint8(_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(uint8(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) { return false; } // Random DS Proof 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(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) { // Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) { // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId) uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Random DS Proof 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(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } // Random DS Proof 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(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[_queryId]; } else return false; // Random DS Proof 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]) { 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 memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) { uint minLength = _length + _toOffset; require(_to.length >= minLength); // Buffer too small. Should be a better way? uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables 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 _success, address _recoveredAddress) { /* 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) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. 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 memory _sig) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(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, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } /* END ORACLIZE_API */ // File: nexusmutual-contracts/contracts/Quotation.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Quotation is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; TokenController internal tc; TokenData internal td; Pool1 internal p1; PoolData internal pd; QuotationData internal qd; MCR internal m1; MemberRoles internal mr; bool internal locked; event RefundEvent(address indexed user, bool indexed status, uint holdedCoverID, bytes32 reason); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); mr = MemberRoles(ms.getLatestAddress("MR")); } function sendEther() public payable { } /** * @dev Expires a cover after a set period of time. * Changes the status of the Cover and reduces the current * sum assured of all areas in which the quotation lies * Unlocks the CN tokens of the cover. Updates the Total Sum Assured value. * @param _cid Cover Id. */ function expireCover(uint _cid) public { require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired)); tf.unlockCN(_cid); bytes4 curr; address scAddress; uint sumAssured; (, , scAddress, curr, sumAssured, ) = qd.getCoverDetailsByCoverID1(_cid); if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted)) _removeSAFromCSA(_cid, sumAssured); qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired)); } /** * @dev Checks if a cover should get expired/closed or not. * @param _cid Cover Index. * @return expire true if the Cover's time has expired, false otherwise. */ function checkCoverExpired(uint _cid) public view returns(bool expire) { expire = qd.getValidityOfCover(_cid) < uint64(now); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function removeSAFromCSA(uint _cid, uint _amount) public onlyInternal { _removeSAFromCSA(_cid, _amount); } /** * @dev Makes Cover funded via NXM tokens. * @param smartCAdd Smart Contract Address */ function makeCoverUsingNXMTokens( uint[] memory coverDetails, uint16 coverPeriod, bytes4 coverCurr, address smartCAdd, uint8 _v, bytes32 _r, bytes32 _s ) public isMemberAndcheckPause { tc.burnFrom(msg.sender, coverDetails[2]); //need burn allowance _verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Verifies cover details signed off chain. * @param from address of funder. * @param scAddress Smart Contract Address */ function verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyInternal { _verifyCoverDetails( from, scAddress, coverCurr, coverDetails, coverPeriod, _v, _r, _s ); } /** * @dev Verifies signature. * @param coverDetails details related to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. * @param _v argument from vrs hash. * @param _r argument from vrs hash. * @param _s argument from vrs hash. */ function verifySign( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA, uint8 _v, bytes32 _r, bytes32 _s ) public view returns(bool) { require(smaratCA != address(0)); require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time"); bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA); return isValidSignature(hash, _v, _r, _s); } /** * @dev Gets order hash for given cover details. * @param coverDetails details realted to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. */ function getOrderHash( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA ) public view returns(bytes32) { return keccak256( abi.encodePacked( coverDetails[0], curr, coverPeriod, smaratCA, coverDetails[1], coverDetails[2], coverDetails[3], coverDetails[4], address(this) ) ); } /** * @dev Verifies signature. * @param hash order hash * @param v argument from vrs hash. * @param r argument from vrs hash. * @param s argument from vrs hash. */ function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == qd.getAuthQuoteEngine()); } /** * @dev to get the status of recently holded coverID * @param userAdd is the user address in concern * @return the status of the concerned coverId */ function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) { uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd); if (holdedCoverLen == 0) { return -1; } else { uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1)); return int(qd.holdedCoverIDStatus(holdedCoverID)); } } /** * @dev to initiate the membership and the cover * @param smartCAdd is the smart contract address to make cover on * @param coverCurr is the currency used to make cover * @param coverDetails list of details related to cover like cover amount, expire time, coverCurrPrice and priceNXM * @param coverPeriod is cover period for which cover is being bought * @param _v argument from vrs hash * @param _r argument from vrs hash * @param _s argument from vrs hash */ function initiateMembershipAndCover( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public payable checkPause { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(!ms.isMember(msg.sender)); require(qd.refundEligible(msg.sender) == false); uint joinFee = td.joiningFee(); uint totalFee = joinFee; if (coverCurr == "ETH") { totalFee = joinFee.add(coverDetails[1]); } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1])); } require(msg.value == totalFee); require(verifySign(coverDetails, coverPeriod, coverCurr, smartCAdd, _v, _r, _s)); qd.addHoldCover(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod); qd.setRefundEligible(msg.sender, true); } /** * @dev to get the verdict of kyc process * @param status is the kyc status * @param _add is the address of member */ function kycVerdict(address _add, bool status) public checkPause noReentrancy { require(msg.sender == qd.kycAuthAddress()); _kycTrigger(status, _add); } /** * @dev transfering Ethers to newly created quotation contract. */ function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy { uint amount = address(this).balance; IERC20 erc20; if (amount > 0) { // newAdd.transfer(amount); Quotation newQT = Quotation(newAdd); newQT.sendEther.value(amount)(); } uint currAssetLen = pd.getAllCurrenciesLen(); for (uint64 i = 1; i < currAssetLen; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); address currAddr = pd.getCurrencyAssetAddress(currName); erc20 = IERC20(currAddr); //solhint-disable-line if (erc20.balanceOf(address(this)) > 0) { require(erc20.transfer(newAdd, erc20.balanceOf(address(this)))); } } } /** * @dev Creates cover of the quotation, changes the status of the quotation , * updates the total sum assured and locks the tokens of the cover against a quote. * @param from Quote member Ethereum address. */ function _makeCover ( //solhint-disable-line address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod ) internal { uint cid = qd.getCoverLength(); qd.addCover(coverPeriod, coverDetails[0], from, coverCurr, scAddress, coverDetails[1], coverDetails[2]); // if cover period of quote is less than 60 days. if (coverPeriod <= 60) { p1.closeCoverOraclise(cid, uint64(uint(coverPeriod).mul(1 days))); } uint coverNoteAmount = (coverDetails[2].mul(qd.tokensRetained())).div(100); tc.mint(from, coverNoteAmount); tf.lockCN(coverNoteAmount, coverPeriod, cid, from); qd.addInTotalSumAssured(coverCurr, coverDetails[0]); qd.addInTotalSumAssuredSC(scAddress, coverCurr, coverDetails[0]); tf.pushStakerRewards(scAddress, coverDetails[2]); } /** * @dev Makes a vover. * @param from address of funder. * @param scAddress Smart Contract Address */ function _verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) internal { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(verifySign(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s)); _makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function _removeSAFromCSA(uint _cid, uint _amount) internal checkPause { address _add; bytes4 coverCurr; (, , _add, coverCurr, , ) = qd.getCoverDetailsByCoverID1(_cid); qd.subFromTotalSumAssured(coverCurr, _amount); qd.subFromTotalSumAssuredSC(_add, coverCurr, _amount); } /** * @dev to trigger the kyc process * @param status is the kyc status * @param _add is the address of member */ function _kycTrigger(bool status, address _add) internal { uint holdedCoverLen = qd.getUserHoldedCoverLength(_add).sub(1); uint holdedCoverID = qd.getUserHoldedCoverByIndex(_add, holdedCoverLen); address payable userAdd; address scAddress; bytes4 coverCurr; uint16 coverPeriod; uint[] memory coverDetails = new uint[](4); IERC20 erc20; (, userAdd, coverDetails) = qd.getHoldedCoverDetailsByID2(holdedCoverID); (, scAddress, coverCurr, coverPeriod) = qd.getHoldedCoverDetailsByID1(holdedCoverID); require(qd.refundEligible(userAdd)); qd.setRefundEligible(userAdd, false); require(qd.holdedCoverIDStatus(holdedCoverID) == uint(QuotationData.HCIDStatus.kycPending)); uint joinFee = td.joiningFee(); if (status) { mr.payJoiningFee.value(joinFee)(userAdd); if (coverDetails[3] > now) { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPass)); address poolAdd = ms.getLatestAddress("P1"); if (coverCurr == "ETH") { p1.sendEther.value(coverDetails[1])(); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(poolAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "KYC Passed"); _makeCover(userAdd, scAddress, coverCurr, coverDetails, coverPeriod); } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPassNoCover)); if (coverCurr == "ETH") { userAdd.transfer(coverDetails[1]); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "Cover Failed"); } } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycFailedOrRefunded)); uint totalRefund = joinFee; if (coverCurr == "ETH") { totalRefund = coverDetails[1].add(joinFee); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } userAdd.transfer(totalRefund); emit RefundEvent(userAdd, status, holdedCoverID, "KYC Failed"); } } } // File: nexusmutual-contracts/contracts/external/uniswap/solidity-interface.sol pragma solidity 0.5.7; contract Factory { function getExchange(address token) public view returns (address); function getToken(address exchange) public view returns (address); } contract Exchange { function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256); function getTokenToEthInputPrice(uint256 tokensSold) public view returns(uint256); function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) public payable returns (uint256); function ethToTokenTransferInput(uint256 minTokens, uint256 deadline, address recipient) public payable returns (uint256); function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline) public payable returns (uint256); function tokenToEthTransferInput(uint256 tokensSold, uint256 minEth, uint256 deadline, address recipient) public payable returns (uint256); function tokenToTokenSwapInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address tokenAddress ) public returns (uint256); function tokenToTokenTransferInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address recipient, address tokenAddress ) public returns (uint256); } // File: nexusmutual-contracts/contracts/Pool2.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Pool2 is Iupgradable { using SafeMath for uint; MCR internal m1; Pool1 internal p1; PoolData internal pd; Factory internal factory; address public uniswapFactoryAddress; uint internal constant DECIMAL1E18 = uint(10) ** 18; bool internal locked; constructor(address _uniswapFactoryAdd) public { uniswapFactoryAddress = _uniswapFactoryAdd; factory = Factory(_uniswapFactoryAdd); } function() external payable {} event Liquidity(bytes16 typeOf, bytes16 functionName); event Rebalancing(bytes4 iaCurr, uint tokenAmount); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev to change the uniswap factory address * @param newFactoryAddress is the new factory address in concern * @return the status of the concerned coverId */ function changeUniswapFactoryAddress(address newFactoryAddress) external onlyInternal { // require(ms.isOwner(msg.sender) || ms.checkIsAuthToGoverned(msg.sender)); uniswapFactoryAddress = newFactoryAddress; factory = Factory(uniswapFactoryAddress); } /** * @dev On upgrade transfer all investment assets and ether to new Investment Pool * @param newPoolAddress New Investment Assest Pool address */ function upgradeInvestmentPool(address payable newPoolAddress) external onlyInternal noReentrancy { uint len = pd.getInvestmentCurrencyLen(); for (uint64 i = 1; i < len; i++) { bytes4 iaName = pd.getInvestmentCurrencyByIndex(i); _upgradeInvestmentPool(iaName, newPoolAddress); } if (address(this).balance > 0) { Pool2 newP2 = Pool2(newPoolAddress); newP2.sendEther.value(address(this).balance)(); } } /** * @dev Internal Swap of assets between Capital * and Investment Sub pool for excess or insufficient * liquidity conditions of a given currency. */ function internalLiquiditySwap(bytes4 curr) external onlyInternal noReentrancy { uint caBalance; uint baseMin; uint varMin; (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { _internalExcessLiquiditySwap(curr, baseMin, varMin, caBalance); } else if (caBalance < uint(baseMin).add(varMin)) { _internalInsufficientLiquiditySwap(curr, baseMin, varMin, caBalance); } } /** * @dev Saves a given investment asset details. To be called daily. * @param curr array of Investment asset name. * @param rate array of investment asset exchange rate. * @param date current date in yyyymmdd. */ function saveIADetails(bytes4[] calldata curr, uint64[] calldata rate, uint64 date, bool bit) external checkPause noReentrancy { bytes4 maxCurr; bytes4 minCurr; uint64 maxRate; uint64 minRate; //ONLY NOTARZIE ADDRESS CAN POST require(pd.isnotarise(msg.sender)); (maxCurr, maxRate, minCurr, minRate) = _calculateIARank(curr, rate); pd.saveIARankDetails(maxCurr, maxRate, minCurr, minRate, date); pd.updatelastDate(date); uint len = curr.length; for (uint i = 0; i < len; i++) { pd.updateIAAvgRate(curr[i], rate[i]); } if (bit) //for testing purpose _rebalancingLiquidityTrading(maxCurr, maxRate); p1.saveIADetailsOracalise(pd.iaRatesTime()); } /** * @dev External Trade for excess or insufficient * liquidity conditions of a given currency. */ function externalLiquidityTrade() external onlyInternal { bool triggerTrade; bytes4 curr; bytes4 minIACurr; bytes4 maxIACurr; uint amount; uint minIARate; uint maxIARate; uint baseMin; uint varMin; uint caBalance; (maxIACurr, maxIARate, minIACurr, minIARate) = pd.getIARankDetailsByDate(pd.getLastDate()); uint len = pd.getAllCurrenciesLen(); for (uint64 i = 0; i < len; i++) { curr = pd.getCurrenciesByIndex(i); (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { //excess amount = caBalance.sub(((uint(baseMin).add(varMin)).mul(3)).div(2)); //*10**18; triggerTrade = _externalExcessLiquiditySwap(curr, minIACurr, amount); } else if (caBalance < uint(baseMin).add(varMin)) { // insufficient amount = (((uint(baseMin).add(varMin)).mul(3)).div(2)).sub(caBalance); triggerTrade = _externalInsufficientLiquiditySwap(curr, maxIACurr, amount); } if (triggerTrade) { p1.triggerExternalLiquidityTrade(); } } } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); pd = PoolData(ms.getLatestAddress("PD")); p1 = Pool1(ms.getLatestAddress("P1")); } function sendEther() public payable { } /** * @dev Gets currency asset balance for a given currency name. */ function _getCurrencyAssetsBalance(bytes4 _curr) public view returns(uint caBalance) { if (_curr == "ETH") { caBalance = address(p1).balance; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); caBalance = erc20.balanceOf(address(p1)); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _transferInvestmentAsset( bytes4 _curr, address _transferTo, uint _amount ) internal { if (_curr == "ETH") { if (_amount > address(this).balance) _amount = address(this).balance; p1.sendEther.value(_amount)(); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (_amount > erc20.balanceOf(address(this))) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(_transferTo, _amount)); } } /** * @dev to perform rebalancing * @param iaCurr is the investment asset currency * @param iaRate is the investment asset rate */ function _rebalancingLiquidityTrading( bytes4 iaCurr, uint64 iaRate ) internal checkPause { uint amountToSell; uint totalRiskBal = pd.getLastVfull(); uint intermediaryEth; uint ethVol = pd.ethVolumeLimit(); totalRiskBal = (totalRiskBal.mul(100000)).div(DECIMAL1E18); Exchange exchange; if (totalRiskBal > 0) { amountToSell = ((totalRiskBal.mul(2).mul( iaRate)).mul(pd.variationPercX100())).div(100 * 100 * 100000); amountToSell = (amountToSell.mul( 10**uint(pd.getInvestmentAssetDecimals(iaCurr)))).div(100); // amount of asset to sell if (iaCurr != "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(iaCurr))); intermediaryEth = exchange.getTokenToEthInputPrice(amountToSell); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amountToSell = (exchange.getEthToTokenInputPrice(intermediaryEth).mul(995)).div(1000); } IERC20 erc20; erc20 = IERC20(pd.getCurrencyAssetAddress(iaCurr)); erc20.approve(address(exchange), amountToSell); exchange.tokenToEthSwapInput(amountToSell, (exchange.getTokenToEthInputPrice( amountToSell).mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else if (iaCurr == "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { _transferInvestmentAsset(iaCurr, ms.getLatestAddress("P1"), amountToSell); } emit Rebalancing(iaCurr, amountToSell); } } /** * @dev Checks whether trading is required for a * given investment asset at a given exchange rate. */ function _checkTradeConditions( bytes4 curr, uint64 iaRate, uint totalRiskBal ) internal view returns(bool check) { if (iaRate > 0) { uint iaBalance = _getInvestmentAssetBalance(curr).div(DECIMAL1E18); if (iaBalance > 0 && totalRiskBal > 0) { uint iaMax; uint iaMin; uint checkNumber; uint z; (iaMin, iaMax) = pd.getInvestmentAssetHoldingPerc(curr); z = pd.variationPercX100(); checkNumber = (iaBalance.mul(100 * 100000)).div(totalRiskBal.mul(iaRate)); if ((checkNumber > ((totalRiskBal.mul(iaMax.add(z))).mul(100000)).div(100)) || (checkNumber < ((totalRiskBal.mul(iaMin.sub(z))).mul(100000)).div(100))) check = true; //eligibleIA } } } /** * @dev Gets the investment asset rank. */ function _getIARank( bytes4 curr, uint64 rateX100, uint totalRiskPoolBalance ) internal view returns (int rhsh, int rhsl) //internal function { uint currentIAmaxHolding; uint currentIAminHolding; uint iaBalance = _getInvestmentAssetBalance(curr); (currentIAminHolding, currentIAmaxHolding) = pd.getInvestmentAssetHoldingPerc(curr); if (rateX100 > 0) { uint rhsf; rhsf = (iaBalance.mul(1000000)).div(totalRiskPoolBalance.mul(rateX100)); rhsh = int(rhsf - currentIAmaxHolding); rhsl = int(rhsf - currentIAminHolding); } } /** * @dev Calculates the investment asset rank. */ function _calculateIARank( bytes4[] memory curr, uint64[] memory rate ) internal view returns( bytes4 maxCurr, uint64 maxRate, bytes4 minCurr, uint64 minRate ) { int max = 0; int min = -1; int rhsh; int rhsl; uint totalRiskPoolBalance; (totalRiskPoolBalance, ) = m1.calVtpAndMCRtp(); uint len = curr.length; for (uint i = 0; i < len; i++) { rhsl = 0; rhsh = 0; if (pd.getInvestmentAssetStatus(curr[i])) { (rhsh, rhsl) = _getIARank(curr[i], rate[i], totalRiskPoolBalance); if (rhsh > max || i == 0) { max = rhsh; maxCurr = curr[i]; maxRate = rate[i]; } if (rhsl < min || rhsl == 0 || i == 0) { min = rhsl; minCurr = curr[i]; minRate = rate[i]; } } } } /** * @dev to get balance of an investment asset * @param _curr is the investment asset in concern * @return the balance */ function _getInvestmentAssetBalance(bytes4 _curr) internal view returns (uint balance) { if (_curr == "ETH") { balance = address(this).balance; } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); balance = erc20.balanceOf(address(this)); } } /** * @dev Creates Excess liquidity trading order for a given currency and a given balance. */ function _internalExcessLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { // require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender)); bytes4 minIACurr; // uint amount; (, , minIACurr, ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == minIACurr) { // amount = _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)); //*10**18; p1.transferCurrencyAsset(_curr, _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2))); } else { p1.triggerExternalLiquidityTrade(); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. */ function _internalInsufficientLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { bytes4 maxIACurr; uint amount; (maxIACurr, , , ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == maxIACurr) { amount = (((_baseMin.add(_varMin)).mul(3)).div(2)).sub(_caBalance); _transferInvestmentAsset(_curr, ms.getLatestAddress("P1"), amount); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); if ((maxIACurr == "ETH" && address(this).balance > 0) || (maxIACurr != "ETH" && erc20.balanceOf(address(this)) > 0)) p1.triggerExternalLiquidityTrade(); } } /** * @dev Creates External excess liquidity trading * order for a given currency and a given balance. * @param curr Currency Asset to Sell * @param minIACurr Investment Asset to Buy * @param amount Amount of Currency Asset to Sell */ function _externalExcessLiquiditySwap( bytes4 curr, bytes4 minIACurr, uint256 amount ) internal returns (bool trigger) { uint intermediaryEth; Exchange exchange; IERC20 erc20; uint ethVol = pd.ethVolumeLimit(); if (curr == minIACurr) { p1.transferCurrencyAsset(curr, amount); } else if (curr == "ETH" && minIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(minIACurr))); if (amount > (address(exchange).balance.mul(ethVol)).div(100)) { // 4% ETH volume limit amount = (address(exchange).balance.mul(ethVol)).div(100); trigger = true; } p1.transferCurrencyAsset(curr, amount); exchange.ethToTokenSwapInput.value(amount) (exchange.getEthToTokenInputPrice(amount).mul(995).div(1000), pd.uniswapDeadline().add(now)); } else if (curr != "ETH" && minIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getTokenToEthInputPrice(amount); trigger = true; } p1.transferCurrencyAsset(curr, amount); // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), amount); exchange.tokenToEthSwapInput(amount, ( intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } Exchange tmp = Exchange(factory.getExchange( pd.getInvestmentAssetAddress(minIACurr))); // minIACurr exchange if (intermediaryEth > address(tmp).balance.mul(ethVol).div(100)) { intermediaryEth = address(tmp).balance.mul(ethVol).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } p1.transferCurrencyAsset(curr, amount); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); erc20.approve(address(exchange), amount); exchange.tokenToTokenSwapInput(amount, (tmp.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), (intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now), pd.getInvestmentAssetAddress(minIACurr)); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. * @param curr Currency Asset to buy * @param maxIACurr Investment Asset to sell * @param amount Amount of Investment Asset to sell */ function _externalInsufficientLiquiditySwap( bytes4 curr, bytes4 maxIACurr, uint256 amount ) internal returns (bool trigger) { Exchange exchange; IERC20 erc20; uint intermediaryEth; // uint ethVol = pd.ethVolumeLimit(); if (curr == maxIACurr) { _transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount); } else if (curr == "ETH" && maxIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); intermediaryEth = exchange.getEthToTokenInputPrice(amount); if (amount > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { amount = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getEthToTokenInputPrice(amount); trigger = true; } erc20 = IERC20(pd.getCurrencyAssetAddress(maxIACurr)); if (intermediaryEth > erc20.balanceOf(address(this))) { intermediaryEth = erc20.balanceOf(address(this)); } // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), intermediaryEth); exchange.tokenToEthTransferInput(intermediaryEth, ( exchange.getTokenToEthInputPrice(intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else if (curr != "ETH" && maxIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > address(this).balance) intermediaryEth = address(this).balance; if (intermediaryEth > (address(exchange).balance.mul (pd.ethVolumeLimit())).div(100)) { // 4% ETH volume limit intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } exchange.ethToTokenTransferInput.value(intermediaryEth)((exchange.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else { address currAdd = pd.getCurrencyAssetAddress(curr); exchange = Exchange(factory.getExchange(currAdd)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } Exchange tmp = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); if (intermediaryEth > address(tmp).balance.mul(pd.ethVolumeLimit()).div(100)) { intermediaryEth = address(tmp).balance.mul(pd.ethVolumeLimit()).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } uint maxIAToSell = tmp.getEthToTokenInputPrice(intermediaryEth); erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); uint maxIABal = erc20.balanceOf(address(this)); if (maxIAToSell > maxIABal) { maxIAToSell = maxIABal; intermediaryEth = tmp.getTokenToEthInputPrice(maxIAToSell); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); } amount = exchange.getEthToTokenInputPrice(intermediaryEth); erc20.approve(address(tmp), maxIAToSell); tmp.tokenToTokenTransferInput(maxIAToSell, ( amount.mul(995)).div(1000), ( intermediaryEth), pd.uniswapDeadline().add(now), address(p1), currAdd); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _upgradeInvestmentPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } } // File: nexusmutual-contracts/contracts/Pool1.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Pool1 is usingOraclize, Iupgradable { using SafeMath for uint; Quotation internal q2; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; Pool2 internal p2; PoolData internal pd; MCR internal m1; Claims public c1; TokenData internal td; bool internal locked; uint internal constant DECIMAL1E18 = uint(10) ** 18; // uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18; event Apiresult(address indexed sender, string msg, bytes32 myid); event Payout(address indexed to, uint coverId, uint tokens); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } function () external payable {} //solhint-disable-line /** * @dev Pays out the sum assured in case a claim is accepted * @param coverid Cover Id. * @param claimid Claim Id. * @return succ true if payout is successful, false otherwise. */ function sendClaimPayout( uint coverid, uint claimid, uint sumAssured, address payable coverHolder, bytes4 coverCurr ) external onlyInternal noReentrancy returns(bool succ) { uint sa = sumAssured.div(DECIMAL1E18); bool check; IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //Payout if (coverCurr == "ETH" && address(this).balance >= sumAssured) { // check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured); coverHolder.transfer(sumAssured); check = true; } else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) { erc20.transfer(coverHolder, sumAssured); check = true; } if (check == true) { q2.removeSAFromCSA(coverid, sa); pd.changeCurrencyAssetVarMin(coverCurr, pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured)); emit Payout(coverHolder, coverid, sumAssured); succ = true; } else { c1.setClaimStatus(claimid, 12); } _triggerExternalLiquidityTrade(); // p2.internalLiquiditySwap(coverCurr); tf.burnStakerLockedToken(coverid, coverCurr, sumAssured); } /** * @dev to trigger external liquidity trade */ function triggerExternalLiquidityTrade() external onlyInternal { _triggerExternalLiquidityTrade(); } ///@dev Oraclize call to close emergency pause. function closeEmergencyPause(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 300000); _saveApiDetails(myid, "EP", 0); } /// @dev Calls the Oraclize Query to close a given Claim after a given period of time. /// @param id Claim Id to be closed /// @param time Time (in seconds) after which Claims assessment voting needs to be closed function closeClaimsOraclise(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000); _saveApiDetails(myid, "CLA", id); } /// @dev Calls Oraclize Query to expire a given Cover after a given period of time. /// @param id Quote Id to be expired /// @param time Time (in seconds) after which the cover should be expired function closeCoverOraclise(uint id, uint64 time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", strConcat( "http://a1.nexusmutual.io/api/Claims/closeClaim_hash/", uint2str(id)), 1000000); _saveApiDetails(myid, "COV", id); } /// @dev Calls the Oraclize Query to initiate MCR calculation. /// @param time Time (in milliseconds) after which the next MCR calculation should be initiated function mcrOraclise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/postMCR/M1", 0); _saveApiDetails(myid, "MCR", 0); } /// @dev Calls the Oraclize Query in case MCR calculation fails. /// @param time Time (in seconds) after which the next MCR calculation should be initiated function mcrOracliseFail(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000); _saveApiDetails(myid, "MCRF", id); } /// @dev Oraclize call to update investment asset rates. function saveIADetailsOracalise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/saveIADetails/M1", 0); _saveApiDetails(myid, "IARB", 0); } /** * @dev Transfers all assest (i.e ETH balance, Currency Assest) from old Pool to new Pool * @param newPoolAddress Address of the new Pool */ function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal { for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 caName = pd.getCurrenciesByIndex(i); _upgradeCapitalPool(caName, newPoolAddress); } if (address(this).balance > 0) { Pool1 newP1 = Pool1(newPoolAddress); newP1.sendEther.value(address(this).balance)(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { m1 = MCR(ms.getLatestAddress("MC")); tk = NXMToken(ms.tokenAddress()); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); pd = PoolData(ms.getLatestAddress("PD")); q2 = Quotation(ms.getLatestAddress("QT")); p2 = Pool2(ms.getLatestAddress("P2")); c1 = Claims(ms.getLatestAddress("CL")); td = TokenData(ms.getLatestAddress("TD")); } function sendEther() public payable { } /** * @dev transfers currency asset to an address * @param curr is the currency of currency asset to transfer * @param amount is amount of currency asset to transfer * @return boolean to represent success or failure */ function transferCurrencyAsset( bytes4 curr, uint amount ) public onlyInternal noReentrancy returns(bool) { return _transferCurrencyAsset(curr, amount); } /// @dev Handles callback of external oracle query. function __callback(bytes32 myid, string memory result) public { result; //silence compiler warning // owner will be removed from production build ms.delegateCallBack(myid); } /// @dev Enables user to purchase cover with funding in ETH. /// @param smartCAdd Smart Contract Address function makeCoverBegin( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause payable { require(msg.value == coverDetails[1]); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Enables user to purchase cover via currency asset eg DAI */ function makeCoverUsingCA( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed"); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /// @dev Enables user to purchase NXM at the current token price. function buyToken() public payable isMember checkPause returns(bool success) { require(msg.value > 0); uint tokenPurchased = _getToken(address(this).balance, msg.value); tc.mint(msg.sender, tokenPurchased); success = true; } /// @dev Sends a given amount of Ether to a given address. /// @param amount amount (in wei) to send. /// @param _add Receiver's address. /// @return succ True if transfer is a success, otherwise False. function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) { require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern"); succ = _add.send(amount); } /** * @dev Allows selling of NXM for ether. * Seller first needs to give this contract allowance to * transfer/burn tokens in the NXMToken contract * @param _amount Amount of NXM to sell * @return success returns true on successfull sale */ function sellNXMTokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) { require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance"); require(!tf.isLockedForMemberVote(msg.sender), "Member voted"); require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit"); uint sellingPrice = _getWei(_amount); tc.burnFrom(msg.sender, _amount); msg.sender.transfer(sellingPrice); success = true; } /** * @dev gives the investment asset balance * @return investment asset balance */ function getInvestmentAssetBalance() public view returns (uint balance) { IERC20 erc20; uint currTokens; for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) { bytes4 currency = pd.getInvestmentCurrencyByIndex(i); erc20 = IERC20(pd.getInvestmentAssetAddress(currency)); currTokens = erc20.balanceOf(address(p2)); if (pd.getIAAvgRate(currency) > 0) balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency))); } balance = balance.add(address(p2).balance); } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function getWei(uint amount) public view returns(uint weiToPay) { return _getWei(amount); } /** * @dev Returns the amount of token a buyer will get for corresponding wei * @param weiPaid Amount of wei * @return tokenToGet Amount of tokens the buyer will get */ function getToken(uint weiPaid) public view returns(uint tokenToGet) { return _getToken((address(this).balance).add(weiPaid), weiPaid); } /** * @dev to trigger external liquidity trade */ function _triggerExternalLiquidityTrade() internal { if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) { pd.setLastLiquidityTradeTrigger(); bytes32 myid = _oraclizeQuery(4, pd.liquidityTradeCallbackTime(), "URL", "", 300000); _saveApiDetails(myid, "ULT", 0); } } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param _amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function _getWei(uint _amount) internal view returns(uint weiToPay) { uint tokenPrice; uint weiPaid; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calVtpAndMCRtp(); while (_amount > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5% if (_amount <= td.priceStep().mul(DECIMAL1E18)) { weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18)); break; } else { _amount = _amount.sub(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18)); weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18); vtp = vtp.sub(weiPaid); weiToPay = weiToPay.add(weiPaid); } } } /** * @dev gives the token * @param _poolBalance is the pool balance * @param _weiPaid is the amount paid in wei * @return the token to get */ function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) { uint tokenPrice; uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18); uint tempTokens; uint superWeiSpent; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid)); require(m1.calculateTokenPrice("ETH") > 0, "Token price can not be zero"); while (superWeiLeft > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tempTokens = superWeiLeft.div(tokenPrice); if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) { tokenToGet = tokenToGet.add(tempTokens); break; } else { tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18)); superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice); superWeiLeft = superWeiLeft.sub(superWeiSpent); vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18)); } } } /** * @dev Save the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal, quote, cover etc. for which oraclize call is made. */ function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal { pd.saveApiDetails(myid, _typeof, id); pd.addInAllApiCall(myid); } /** * @dev transfers currency asset * @param _curr is currency of asset to transfer * @param _amount is the amount to be transferred * @return boolean representing the success of transfer */ function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) { if (_curr == "ETH") { if (address(this).balance < _amount) _amount = address(this).balance; p2.sendEther.value(_amount)(); succ = true; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line if (erc20.balanceOf(address(this)) < _amount) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(address(p2), _amount)); succ = true; } } /** * @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade. */ function _upgradeCapitalPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } /** * @dev oraclize query * @param paramCount is number of paramters passed * @param timestamp is the current timestamp * @param datasource in concern * @param arg in concern * @param gasLimit required for query * @return id of oraclize query */ function _oraclizeQuery( uint paramCount, uint timestamp, string memory datasource, string memory arg, uint gasLimit ) internal returns (bytes32 id) { if (paramCount == 4) { id = oraclize_query(timestamp, datasource, arg, gasLimit); } else if (paramCount == 3) { id = oraclize_query(timestamp, datasource, arg); } else { id = oraclize_query(datasource, arg); } } } // File: nexusmutual-contracts/contracts/MCR.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MCR is Iupgradable { using SafeMath for uint; Pool1 internal p1; PoolData internal pd; NXMToken internal tk; QuotationData internal qd; MemberRoles internal mr; TokenData internal td; ProposalCategory internal proposalCategory; uint private constant DECIMAL1E18 = uint(10) ** 18; uint private constant DECIMAL1E05 = uint(10) ** 5; uint private constant DECIMAL1E19 = uint(10) ** 19; uint private constant minCapFactor = uint(10) ** 21; uint public variableMincap; uint public dynamicMincapThresholdx100 = 13000; uint public dynamicMincapIncrementx100 = 100; event MCREvent( uint indexed date, uint blockNumber, bytes4[] allCurr, uint[] allCurrRates, uint mcrEtherx100, uint mcrPercx100, uint vFull ); /** * @dev Adds new MCR data. * @param mcrP Minimum Capital Requirement in percentage. * @param vF Pool1 fund value in Ether used in the last full daily calculation of the Capital model. * @param onlyDate Date(yyyymmdd) at which MCR details are getting added. */ function addMCRData( uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate ) external checkPause { require(proposalCategory.constructorCheck()); require(pd.isnotarise(msg.sender)); if (mr.launched() && pd.capReached() != 1) { if (mcrP >= 10000) pd.setCapReached(1); } uint len = pd.getMCRDataLength(); _addMCRData(len, onlyDate, curr, mcrE, mcrP, vF, _threeDayAvg); } /** * @dev Adds MCR Data for last failed attempt. */ function addLastMCRData(uint64 date) external checkPause onlyInternal { uint64 lastdate = uint64(pd.getLastMCRDate()); uint64 failedDate = uint64(date); if (failedDate >= lastdate) { uint mcrP; uint mcrE; uint vF; (mcrP, mcrE, vF, ) = pd.getLastMCR(); uint len = pd.getAllCurrenciesLen(); pd.pushMCRData(mcrP, mcrE, vF, date); for (uint j = 0; j < len; j++) { bytes4 currName = pd.getCurrenciesByIndex(j); pd.updateCAAvgRate(currName, pd.getCAAvgRate(currName)); } emit MCREvent(date, block.number, new bytes4[](0), new uint[](0), mcrE, mcrP, vF); // Oraclize call for next MCR calculation _callOracliseForMCR(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); tk = NXMToken(ms.tokenAddress()); mr = MemberRoles(ms.getLatestAddress("MR")); td = TokenData(ms.getLatestAddress("TD")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Gets total sum assured(in ETH). * @return amount of sum assured */ function getAllSumAssurance() public view returns(uint amount) { uint len = pd.getAllCurrenciesLen(); for (uint i = 0; i < len; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); if (currName == "ETH") { amount = amount.add(qd.getTotalSumAssured(currName)); } else { if (pd.getCAAvgRate(currName) > 0) amount = amount.add((qd.getTotalSumAssured(currName).mul(100)).div(pd.getCAAvgRate(currName))); } } } /** * @dev Calculates V(Tp) and MCR%(Tp), i.e, Pool Fund Value in Ether * and MCR% used in the Token Price Calculation. * @return vtp Pool Fund Value in Ether used for the Token Price Model * @return mcrtp MCR% used in the Token Price Model. */ function _calVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { vtp = 0; IERC20 erc20; uint currTokens = 0; uint i; for (i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 currency = pd.getCurrenciesByIndex(i); erc20 = IERC20(pd.getCurrencyAssetAddress(currency)); currTokens = erc20.balanceOf(address(p1)); if (pd.getCAAvgRate(currency) > 0) vtp = vtp.add((currTokens.mul(100)).div(pd.getCAAvgRate(currency))); } vtp = vtp.add(poolBalance).add(p1.getInvestmentAssetBalance()); uint mcrFullperc; uint vFull; (mcrFullperc, , vFull, ) = pd.getLastMCR(); if (vFull > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); } } /** * @dev Calculates the Token Price of NXM in a given currency. * @param curr Currency name. */ function calculateStepTokenPrice( bytes4 curr, uint mcrtp ) public view onlyInternal returns(uint tokenPrice) { return _calculateTokenPrice(curr, mcrtp); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param curr Currency name. */ function calculateTokenPrice (bytes4 curr) public view returns(uint tokenPrice) { uint mcrtp; (, mcrtp) = _calVtpAndMCRtp(address(p1).balance); return _calculateTokenPrice(curr, mcrtp); } function calVtpAndMCRtp() public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(address(p1).balance); } function calculateVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(poolBalance); } function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) public view returns(uint lowerThreshold, uint upperThreshold) { minCap = (minCap.mul(minCapFactor)).add(variableMincap); uint lower = 0; if (vtp >= vF) { upperThreshold = vtp.mul(120).mul(100).div((minCap)); //Max Threshold = [MAX(Vtp, Vfull) x 120] / mcrMinCap } else { upperThreshold = vF.mul(120).mul(100).div((minCap)); } if (vtp > 0) { lower = totalSA.mul(DECIMAL1E18).mul(pd.shockParameter()).div(100); if(lower < minCap.mul(11).div(10)) lower = minCap.mul(11).div(10); } if (lower > 0) { //Min Threshold = [Vtp / MAX(TotalActiveSA x ShockParameter, mcrMinCap x 1.1)] x 100 lowerThreshold = vtp.mul(100).mul(100).div(lower); } } /** * @dev Gets max numbers of tokens that can be sold at the moment. */ function getMaxSellTokens() public view returns(uint maxTokens) { uint baseMin = pd.getCurrencyAssetBaseMin("ETH"); uint maxTokensAccPoolBal; if (address(p1).balance > baseMin.mul(50).div(100)) { maxTokensAccPoolBal = address(p1).balance.sub( (baseMin.mul(50)).div(100)); } maxTokensAccPoolBal = (maxTokensAccPoolBal.mul(DECIMAL1E18)).div( (calculateTokenPrice("ETH").mul(975)).div(1000)); uint lastMCRPerc = pd.getLastMCRPerc(); if (lastMCRPerc > 10000) maxTokens = (((uint(lastMCRPerc).sub(10000)).mul(2000)).mul(DECIMAL1E18)).div(10000); if (maxTokens > maxTokensAccPoolBal) maxTokens = maxTokensAccPoolBal; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "DMCT") { val = dynamicMincapThresholdx100; } else if (code == "DMCI") { val = dynamicMincapIncrementx100; } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "DMCT") { dynamicMincapThresholdx100 = val; } else if (code == "DMCI") { dynamicMincapIncrementx100 = val; } else { revert("Invalid param code"); } } /** * @dev Calls oraclize query to calculate MCR details after 24 hours. */ function _callOracliseForMCR() internal { p1.mcrOraclise(pd.mcrTime()); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param _curr Currency name. * @return tokenPrice Token price. */ function _calculateTokenPrice( bytes4 _curr, uint mcrtp ) internal view returns(uint tokenPrice) { uint getA; uint getC; uint getCAAvgRate; uint tokenExponentValue = td.tokenExponent(); // uint max = (mcrtp.mul(mcrtp).mul(mcrtp).mul(mcrtp)); uint max = mcrtp ** tokenExponentValue; uint dividingFactor = tokenExponentValue.mul(4); (getA, getC, getCAAvgRate) = pd.getTokenPriceDetails(_curr); uint mcrEth = pd.getLastMCREther(); getC = getC.mul(DECIMAL1E18); tokenPrice = (mcrEth.mul(DECIMAL1E18).mul(max).div(getC)).div(10 ** dividingFactor); tokenPrice = tokenPrice.add(getA.mul(DECIMAL1E18).div(DECIMAL1E05)); tokenPrice = tokenPrice.mul(getCAAvgRate * 10); tokenPrice = (tokenPrice).div(10**3); } /** * @dev Adds MCR Data. Checks if MCR is within valid * thresholds in order to rule out any incorrect calculations */ function _addMCRData( uint len, uint64 newMCRDate, bytes4[] memory curr, uint mcrE, uint mcrP, uint vF, uint[] memory _threeDayAvg ) internal { uint vtp = 0; uint lowerThreshold = 0; uint upperThreshold = 0; if (len > 1) { (vtp, ) = _calVtpAndMCRtp(address(p1).balance); (lowerThreshold, upperThreshold) = getThresholdValues(vtp, vF, getAllSumAssurance(), pd.minCap()); } if(mcrP > dynamicMincapThresholdx100) variableMincap = (variableMincap.mul(dynamicMincapIncrementx100.add(10000)).add(minCapFactor.mul(pd.minCap().mul(dynamicMincapIncrementx100)))).div(10000); // Explanation for above formula :- // actual formula -> variableMinCap = variableMinCap + (variableMinCap+minCap)*dynamicMincapIncrement/100 // Implemented formula is simplified form of actual formula. // Let consider above formula as b = b + (a+b)*c/100 // here, dynamicMincapIncrement is in x100 format. // so b+(a+b)*cx100/10000 can be written as => (10000.b + b.cx100 + a.cx100)/10000. // It can further simplify to (b.(10000+cx100) + a.cx100)/10000. if (len == 1 || (mcrP) >= lowerThreshold && (mcrP) <= upperThreshold) { vtp = pd.getLastMCRDate(); // due to stack to deep error,we are reusing already declared variable pd.pushMCRData(mcrP, mcrE, vF, newMCRDate); for (uint i = 0; i < curr.length; i++) { pd.updateCAAvgRate(curr[i], _threeDayAvg[i]); } emit MCREvent(newMCRDate, block.number, curr, _threeDayAvg, mcrE, mcrP, vF); // Oraclize call for next MCR calculation if (vtp < newMCRDate) { _callOracliseForMCR(); } } else { p1.mcrOracliseFail(newMCRDate, pd.mcrFailTime()); } } } // File: nexusmutual-contracts/contracts/Claims.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Claims is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; NXMToken internal tk; TokenController internal tc; ClaimsReward internal cr; Pool1 internal p1; ClaimsData internal cd; TokenData internal td; PoolData internal pd; Pool2 internal p2; QuotationData internal qd; MCR internal m1; uint private constant DECIMAL1E18 = uint(10) ** 18; /** * @dev Sets the status of claim using claim id. * @param claimId claim id. * @param stat status to be set. */ function setClaimStatus(uint claimId, uint stat) external onlyInternal { _setClaimStatus(claimId, stat); } /** * @dev Gets claim details of claim id = pending claim start + given index */ function getClaimFromNewStart( uint index ) external view returns ( uint coverId, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { (coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender); // status = rewardStatus[statusnumber].claimStatusDesc; } /** * @dev Gets details of a claim submitted by the calling user, at a given index */ function getUserClaimByIndex( uint index ) external view returns( uint status, uint coverId, uint claimId ) { uint statusno; (statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender); status = statusno; } /** * @dev Gets details of a given claim id. * @param _claimId Claim Id. * @return status Current status of claim id * @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial * @return claimOwner Address through which claim is submitted * @return coverId Coverid associated with the claim id */ function getClaimbyIndex(uint _claimId) external view returns ( uint claimId, uint status, int8 finalVerdict, address claimOwner, uint coverId ) { uint stat; claimId = _claimId; (, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId); claimOwner = qd.getCoverMemberAddress(coverId); status = stat; } /** * @dev Calculates total amount that has been used to assess a claim. * Computaion:Adds acceptCA(tokens used for voting in favor of a claim) * denyCA(tokens used for voting against a claim) * current token price. * @param claimId Claim Id. * @param member Member type 0 -> Claim Assessors, else members. * @return tokens Total Amount used in Claims assessment. */ function getCATokens(uint claimId, uint member) external view returns(uint tokens) { uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; if (member == 0) { (, accept, deny) = cd.getClaimsTokenCA(claimId); } else { (, accept, deny) = cd.getClaimsTokenMV(claimId); } tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens) } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); cr = ClaimsReward(ms.getLatestAddress("CR")); cd = ClaimsData(ms.getLatestAddress("CD")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function changePendingClaimStart() public onlyInternal { uint origstat; uint state12Count; uint pendingClaimStart = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = pendingClaimStart; i < actualClaimLength; i++) { (, , , origstat, , state12Count) = cd.getClaim(i); if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60))) cd.setpendingClaimStart(i); else break; } } /** * @dev Submits a claim for a given cover note. * Adds claim to queue incase of emergency pause else directly submits the claim. * @param coverId Cover Id. */ function submitClaim(uint coverId) public { address qadd = qd.getCoverMemberAddress(coverId); require(qadd == msg.sender); uint8 cStatus; (, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId); require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted"); require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired"); if (ms.isPause() == false) { _addClaim(coverId, now, qadd); } else { cd.setClaimAtEmergencyPause(coverId, now, false); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested)); } } /** * @dev Submits the Claims queued once the emergency pause is switched off. */ function submitClaimAfterEPOff() public onlyInternal { uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP(); uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP(); uint coverId; uint dateUpd; bool submit; address qadd; for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) { (coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i); require(submit == false); qadd = qd.getCoverMemberAddress(coverId); _addClaim(coverId, dateUpd, qadd); cd.setClaimSubmittedAtEPTrue(i, true); } cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP); } /** * @dev Castes vote for members who have tokens locked under Claims Assessment * @param claimId claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict); uint voteLength = cd.getAllVoteLength(); cd.addClaimVoteCA(claimId, voteLength); cd.setUserClaimVoteCA(msg.sender, claimId, voteLength); cd.setClaimTokensCA(claimId, verdict, tokens); tc.extendLockOf(msg.sender, "CLA", td.lockCADays()); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Submits a member vote for assessing a claim. * Tokens other than those locked under Claims * Assessment can be used to cast a vote for a given claim id. * @param claimId Selected claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); uint stat; uint tokens = tc.totalBalanceOf(msg.sender); (, stat) = cd.getClaimStatusNumber(claimId); require(stat >= 1 && stat <= 5); require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict); tc.lockForMemberVote(msg.sender, td.lockMVDays()); uint voteLength = cd.getAllVoteLength(); cd.addClaimVotemember(claimId, voteLength); cd.setUserClaimVoteMember(msg.sender, claimId, voteLength); cd.setClaimTokensMV(claimId, verdict, tokens); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Pause Voting of All Pending Claims when Emergency Pause Start. */ function pauseAllPendingClaimsVoting() public onlyInternal { uint firstIndex = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = firstIndex; i < actualClaimLength; i++) { if (checkVoteClosing(i) == 0) { uint dateUpd = cd.getClaimDateUpd(i); cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false); } } } /** * @dev Resume the voting phase of all Claims paused due to an emergency pause. */ function startAllPendingClaimsVoting() public onlyInternal { uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP(); uint i; uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause(); for (i = firstIndx; i < lengthOfClaimVotingPause; i++) { uint pendingTime; uint claimID; (claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i); uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime); cd.setClaimdateUpd(claimID, pTime); cd.setPendingClaimVoteStatus(i, true); uint coverid; (, coverid) = cd.getClaimCoverId(claimID); address qadd = qd.getCoverMemberAddress(coverid); tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime())); p1.closeClaimsOraclise(claimID, uint64(pTime)); } cd.setFirstClaimIndexToStartVotingAfterEP(i); } /** * @dev Checks if voting of a claim should be closed or not. * @param claimId Claim Id. * @return close 1 -> voting should be closed, 0 -> if voting should not be closed, * -1 -> voting has already been closed. */ function checkVoteClosing(uint claimId) public view returns(int8 close) { close = 0; uint status; (, status) = cd.getClaimStatusNumber(claimId); uint dateUpd = cd.getClaimDateUpd(claimId); if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) { if (cd.getClaimState12Count(claimId) < 60) close = 1; } if (status > 5 && status != 12) { close = -1; } else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) { close = 1; } else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) { close = 0; } else if (status == 0 || (status >= 1 && status <= 5)) { close = _checkVoteClosingFinal(claimId, status); } } /** * @dev Checks if voting of a claim should be closed or not. * Internally called by checkVoteClosing method * for Claims whose status number is 0 or status number lie between 2 and 6. * @param claimId Claim Id. * @param status Current status of claim. * @return close 1 if voting should be closed,0 in case voting should not be closed, * -1 if voting has already been closed. */ function _checkVoteClosingFinal(uint claimId, uint status) internal view returns(int8 close) { close = 0; uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; (, accept, deny) = cd.getClaimsTokenCA(claimId); uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); (, accept, deny) = cd.getClaimsTokenMV(claimId); uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); if (status == 0 && caTokens >= sumassured.mul(10)) { close = 1; } else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) { close = 1; } } /** * @dev Changes the status of an existing claim id, based on current * status and current conditions of the system * @param claimId Claim Id. * @param stat status number. */ function _setClaimStatus(uint claimId, uint stat) internal { uint origstat; uint state12Count; uint dateUpd; uint coverId; (, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId); (, origstat) = cd.getClaimStatusNumber(claimId); if (stat == 12 && origstat == 12) { cd.updateState12Count(claimId, 1); } cd.setClaimStatus(claimId, stat); if (state12Count >= 60 && stat == 12) { cd.setClaimStatus(claimId, 13); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied)); } uint time = now; cd.setClaimdateUpd(claimId, time); if (stat >= 2 && stat <= 5) { p1.closeClaimsOraclise(claimId, cd.maxVotingTime()); } if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) { p1.closeClaimsOraclise(claimId, cd.payoutRetryTime()); } else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) { uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now)); p1.closeClaimsOraclise(claimId, timeLeft); } } /** * @dev Submits a claim for a given cover note. * Set deposits flag against cover. */ function _addClaim(uint coverId, uint time, address add) internal { tf.depositCN(coverId); uint len = cd.actualClaimLength(); cd.addClaim(len, coverId, add, now); cd.callClaimEvent(coverId, add, len, time); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted)); bytes4 curr = qd.getCurrencyOfCover(coverId); uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured)); p2.internalLiquiditySwap(curr); p1.closeClaimsOraclise(len, cd.maxVotingTime()); } } // File: nexusmutual-contracts/contracts/ClaimsReward.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ //Claims Reward Contract contains the functions for calculating number of tokens // that will get rewarded, unlocked or burned depending upon the status of claim. pragma solidity 0.5.7; contract ClaimsReward is Iupgradable { using SafeMath for uint; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; TokenData internal td; QuotationData internal qd; Claims internal c1; ClaimsData internal cd; Pool1 internal p1; Pool2 internal p2; PoolData internal pd; Governance internal gv; IPooledStaking internal pooledStaking; uint private constant DECIMAL1E18 = uint(10) ** 18; function changeDependentContractAddress() public onlyInternal { c1 = Claims(ms.getLatestAddress("CL")); cd = ClaimsData(ms.getLatestAddress("CD")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /// @dev Decides the next course of action for a given claim. function changeClaimStatus(uint claimid) public checkPause onlyInternal { uint coverid; (, coverid) = cd.getClaimCoverId(claimid); uint status; (, status) = cd.getClaimStatusNumber(claimid); // when current status is "Pending-Claim Assessor Vote" if (status == 0) { _changeClaimStatusCA(claimid, coverid, status); } else if (status >= 1 && status <= 5) { _changeClaimStatusMV(claimid, coverid, status); } else if (status == 12) { // when current status is "Claim Accepted Payout Pending" uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); address payable coverHolder = qd.getCoverMemberAddress(coverid); bytes4 coverCurrency = qd.getCurrencyOfCover(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, coverHolder, coverCurrency); if (success) { tf.burnStakedTokens(coverid, coverCurrency, sumAssured); c1.setClaimStatus(claimid, 14); } } c1.changePendingClaimStart(); } /// @dev Amount of tokens to be rewarded to a user for a particular vote id. /// @param check 1 -> CA vote, else member vote /// @param voteid vote id for which reward has to be Calculated /// @param flag if 1 calculate even if claimed,else don't calculate if already claimed /// @return tokenCalculated reward to be given for vote id /// @return lastClaimedCheck true if final verdict is still pending for that voteid /// @return tokens number of tokens locked under that voteid /// @return perc percentage of reward to be given. function getRewardToBeGiven( uint check, uint voteid, uint flag ) public view returns ( uint tokenCalculated, bool lastClaimedCheck, uint tokens, uint perc ) { uint claimId; int8 verdict; bool claimed; uint tokensToBeDist; uint totalTokens; (tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid); lastClaimedCheck = false; int8 claimVerdict = cd.getFinalVerdict(claimId); if (claimVerdict == 0) { lastClaimedCheck = true; } if (claimVerdict == verdict && (claimed == false || flag == 1)) { if (check == 1) { (perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId); } else { (, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId); } if (perc > 0) { if (check == 1) { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenCA(claimId); } else { (, , totalTokens) = cd.getClaimsTokenCA(claimId); } } else { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenMV(claimId); }else { (, , totalTokens) = cd.getClaimsTokenMV(claimId); } } tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100)); } } } /// @dev Transfers all tokens held by contract to a new contract in case of upgrade. function upgrade(address _newAdd) public onlyInternal { uint amount = tk.balanceOf(address(this)); if (amount > 0) { require(tk.transfer(_newAdd, amount)); } } /// @dev Total reward in token due for claim by a user. /// @return total total number of tokens function getRewardToBeDistributedByUser(address _add) public view returns(uint total) { uint lengthVote = cd.getVoteAddressCALength(_add); uint lastIndexCA; uint lastIndexMV; uint tokenForVoteId; uint voteId; (lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add); for (uint i = lastIndexCA; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(_add, i); (tokenForVoteId, , , ) = getRewardToBeGiven(1, voteId, 0); total = total.add(tokenForVoteId); } lengthVote = cd.getVoteAddressMemberLength(_add); for (uint j = lastIndexMV; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(_add, j); (tokenForVoteId, , , ) = getRewardToBeGiven(0, voteId, 0); total = total.add(tokenForVoteId); } return (total); } /// @dev Gets reward amount and claiming status for a given claim id. /// @return reward amount of tokens to user. /// @return claimed true if already claimed false if yet to be claimed. function getRewardAndClaimedStatus(uint check, uint claimId) public view returns(uint reward, bool claimed) { uint voteId; uint claimid; uint lengthVote; if (check == 1) { lengthVote = cd.getVoteAddressCALength(msg.sender); for (uint i = 0; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(msg.sender, i); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } else { lengthVote = cd.getVoteAddressMemberLength(msg.sender); for (uint j = 0; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(msg.sender, j); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } (reward, , , ) = getRewardToBeGiven(check, voteId, 1); } /** * @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance * Claim assesment, Risk assesment, Governance rewards */ function claimAllPendingReward(uint records) public isMemberAndcheckPause { _claimRewardToBeDistributed(records); pooledStaking.withdrawReward(msg.sender); uint governanceRewards = gv.claimReward(msg.sender, records); if (governanceRewards > 0) { require(tk.transfer(msg.sender, governanceRewards)); } } /** * @dev Function used to get pending rewards of a particular user address. * @param _add user address. * @return total reward amount of the user */ function getAllPendingRewardOfUser(address _add) public view returns(uint) { uint caReward = getRewardToBeDistributedByUser(_add); uint pooledStakingReward = pooledStaking.stakerReward(_add); uint governanceReward = gv.getPendingReward(_add); return caReward.add(pooledStakingReward).add(governanceReward); } /// @dev Rewards/Punishes users who participated in Claims assessment. // Unlocking and burning of the tokens will also depend upon the status of claim. /// @param claimid Claim Id. function _rewardAgainstClaim(uint claimid, uint coverid, uint sumAssured, uint status) internal { uint premiumNXM = qd.getCoverPremiumNXM(coverid); bytes4 curr = qd.getCurrencyOfCover(coverid); uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100);// 20% of premium uint percCA; uint percMV; (percCA, percMV) = cd.getRewardStatus(status); cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens); if (percCA > 0 || percMV > 0) { tc.mint(address(this), distributableTokens); } if (status == 6 || status == 9 || status == 11) { cd.changeFinalVerdict(claimid, -1); td.setDepositCN(coverid, false); // Unset flag tf.burnDepositCN(coverid); // burn Deposited CN pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).sub(sumAssured)); p2.internalLiquiditySwap(curr); } else if (status == 7 || status == 8 || status == 10) { cd.changeFinalVerdict(claimid, 1); td.setDepositCN(coverid, false); // Unset flag tf.unlockCN(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, qd.getCoverMemberAddress(coverid), curr); if (success) { tf.burnStakedTokens(coverid, curr, sumAssured); } } } /// @dev Computes the result of Claim Assessors Voting for a given claim id. function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency. uint accept; uint deny; uint acceptAndDeny; bool rewardOrPunish; uint sumAssured; (, accept) = cd.getClaimVote(claimid, 1); (, deny) = cd.getClaimVote(claimid, -1); acceptAndDeny = accept.add(deny); accept = accept.mul(100); deny = deny.mul(100); if (caTokens == 0) { status = 3; } else { sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); // Min threshold reached tokens used for voting > 5* sum assured if (caTokens > sumAssured.mul(5)) { if (accept.div(acceptAndDeny) > 70) { status = 7; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted)); rewardOrPunish = true; } else if (deny.div(acceptAndDeny) > 70) { status = 6; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied)); rewardOrPunish = true; } else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 4; } else { status = 5; } } else { if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 2; } else { status = 3; } } } c1.setClaimStatus(claimid, status); if (rewardOrPunish) { _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } } /// @dev Computes the result of Member Voting for a given claim id. function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint8 coverStatus; uint statusOrig = status; uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency. // If tokens used for acceptance >50%, claim is accepted uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); uint thresholdUnreached = 0; // Minimum threshold for member voting is reached only when // value of tokens used for voting > 5* sum assured of claim id if (mvTokens < sumAssured.mul(5)) { thresholdUnreached = 1; } uint accept; (, accept) = cd.getClaimMVote(claimid, 1); uint deny; (, deny) = cd.getClaimMVote(claimid, -1); if (accept.add(deny) > 0) { if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 8; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 9; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } } if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) { status = 10; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) { status = 11; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } c1.setClaimStatus(claimid, status); qd.changeCoverStatusNo(coverid, uint8(coverStatus)); // Reward/Punish Claim Assessors and Members who participated in Claims assessment _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } /// @dev Allows a user to claim all pending Claims assessment rewards. function _claimRewardToBeDistributed(uint _records) internal { uint lengthVote = cd.getVoteAddressCALength(msg.sender); uint voteid; uint lastIndex; (lastIndex, ) = cd.getRewardDistributedIndex(msg.sender); uint total = 0; uint tokenForVoteId = 0; bool lastClaimedCheck; uint _days = td.lockCADays(); bool claimed; uint counter = 0; uint claimId; uint perc; uint i; uint lastClaimed = lengthVote; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressCA(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (perc > 0 && !claimed) { counter++; cd.setRewardClaimed(voteid, true); } else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) { (perc, , ) = cd.getClaimRewardDetail(claimId); if (perc == 0) { counter++; } cd.setRewardClaimed(voteid, true); } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexCA(msg.sender, i); } else { cd.setRewardDistributedIndexCA(msg.sender, lastClaimed); } lengthVote = cd.getVoteAddressMemberLength(msg.sender); lastClaimed = lengthVote; _days = _days.mul(counter); if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) { tc.reduceLock(msg.sender, "CLA", _days); } (, lastIndex) = cd.getRewardDistributedIndex(msg.sender); lastClaimed = lengthVote; counter = 0; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressMember(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , ) = getRewardToBeGiven(0, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (claimed == false && cd.getFinalVerdict(claimId) != 0) { cd.setRewardClaimed(voteid, true); counter++; } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (total > 0) { require(tk.transfer(msg.sender, total)); } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexMV(msg.sender, i); } else { cd.setRewardDistributedIndexMV(msg.sender, lastClaimed); } } /** * @dev Function used to claim the commission earned by the staker. */ function _claimStakeCommission(uint _records, address _user) external onlyInternal { uint total=0; uint len = td.getStakerStakedContractLength(_user); uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user); uint commissionEarned; uint commissionRedeemed; uint maxCommission; uint lastCommisionRedeemed = len; uint counter; uint i; for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) { commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i); commissionEarned = td.getStakerEarnedStakeCommission(_user, i); maxCommission = td.getStakerInitialStakedAmountOnContract( _user, i).mul(td.stakerMaxCommissionPer()).div(100); if (lastCommisionRedeemed == len && maxCommission != commissionEarned) lastCommisionRedeemed = i; td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed)); total = total.add(commissionEarned.sub(commissionRedeemed)); counter++; } if (lastCommisionRedeemed == len) { td.setLastCompletedStakeCommissionIndex(_user, i); } else { td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed); } if (total > 0) require(tk.transfer(_user, total)); //solhint-disable-line } } // File: nexusmutual-contracts/contracts/MemberRoles.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MemberRoles is IMemberRoles, Governed, Iupgradable { TokenController public dAppToken; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; TokenFunctions internal tf; NXMToken public tk; struct MemberRoleDetails { uint memberCounter; mapping(address => bool) memberActive; address[] memberAddress; address authorized; } enum Role {UnAssigned, AdvisoryBoard, Member, Owner} event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp); MemberRoleDetails[] internal memberRoleData; bool internal constructorCheck; uint public maxABCount; bool public launched; uint public launchedOn; modifier checkRoleAuthority(uint _memberRoleId) { if (memberRoleData[_memberRoleId].authorized != address(0)) require(msg.sender == memberRoleData[_memberRoleId].authorized); else require(isAuthorizedToGovern(msg.sender), "Not Authorized"); _; } /** * @dev to swap advisory board member * @param _newABAddress is address of new AB member * @param _removeAB is advisory board member to be removed */ function swapABMember ( address _newABAddress, address _removeAB ) external checkRoleAuthority(uint(Role.AdvisoryBoard)) { _updateRole(_newABAddress, uint(Role.AdvisoryBoard), true); _updateRole(_removeAB, uint(Role.AdvisoryBoard), false); } /** * @dev to swap the owner address * @param _newOwnerAddress is the new owner address */ function swapOwner ( address _newOwnerAddress ) external { require(msg.sender == address(ms)); _updateRole(ms.owner(), uint(Role.Owner), false); _updateRole(_newOwnerAddress, uint(Role.Owner), true); } /** * @dev is used to add initital advisory board members * @param abArray is the list of initial advisory board members */ function addInitialABMembers(address[] calldata abArray) external onlyOwner { //Ensure that NXMaster has initialized. require(ms.masterInitialized()); require(maxABCount >= SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length) ); //AB count can't exceed maxABCount for (uint i = 0; i < abArray.length; i++) { require(checkRole(abArray[i], uint(MemberRoles.Role.Member))); _updateRole(abArray[i], uint(Role.AdvisoryBoard), true); } } /** * @dev to change max number of AB members allowed * @param _val is the new value to be set */ function changeMaxABCount(uint _val) external onlyInternal { maxABCount = _val; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { td = TokenData(ms.getLatestAddress("TD")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); tf = TokenFunctions(ms.getLatestAddress("TF")); tk = NXMToken(ms.tokenAddress()); dAppToken = TokenController(ms.getLatestAddress("TC")); } /** * @dev to change the master address * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev to initiate the member roles * @param _firstAB is the address of the first AB member * @param memberAuthority is the authority (role) of the member */ function memberRolesInitiate (address _firstAB, address memberAuthority) public { require(!constructorCheck); _addInitialMemberRoles(_firstAB, memberAuthority); constructorCheck = true; } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole( //solhint-disable-line bytes32 _roleName, string memory _roleDescription, address _authorized ) public onlyAuthorizedToGovern { _addRole(_roleName, _roleDescription, _authorized); } /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole( //solhint-disable-line address _memberAddress, uint _roleId, bool _active ) public checkRoleAuthority(_roleId) { _updateRole(_memberAddress, _roleId, _active); } /** * @dev to add members before launch * @param userArray is list of addresses of members * @param tokens is list of tokens minted for each array element */ function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner { require(!launched); for (uint i=0; i < userArray.length; i++) { require(!ms.isMember(userArray[i])); dAppToken.addToWhitelist(userArray[i]); _updateRole(userArray[i], uint(Role.Member), true); dAppToken.mint(userArray[i], tokens[i]); } launched = true; launchedOn = now; } /** * @dev Called by user to pay joining membership fee */ function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } } /** * @dev to perform kyc verdict * @param _userAddress whose kyc is being performed * @param verdict of kyc process */ function kycVerdict(address payable _userAddress, bool verdict) public { require(msg.sender == qd.kycAuthAddress()); require(!ms.isPause()); require(_userAddress != address(0)); require(!ms.isMember(_userAddress)); require(qd.refundEligible(_userAddress)); if (verdict) { qd.setRefundEligible(_userAddress, false); uint fee = td.joiningFee(); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(fee); //solhint-disable-line } else { qd.setRefundEligible(_userAddress, false); _userAddress.transfer(td.joiningFee()); //solhint-disable-line } } /** * @dev Called by existed member if wish to Withdraw membership. */ function withdrawMembership() public { require(!ms.isPause() && ms.isMember(msg.sender)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist } /** * @dev Called by existed member if wish to switch membership to other address. * @param _add address of user to forward membership. */ function switchMembership(address _add) external { require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.addToWhitelist(_add); _updateRole(_add, uint(Role.Member), true); tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); emit switchedMembership(msg.sender, _add, now); } /// @dev Return number of member roles function totalRoles() public view returns(uint256) { //solhint-disable-line return memberRoleData.length; } /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _newAuthorized New authorized address against role id function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) { //solhint-disable-line memberRoleData[_roleId].authorized = _newAuthorized; } /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory memberArray) { //solhint-disable-line uint length = memberRoleData[_memberRoleId].memberAddress.length; uint i; uint j = 0; memberArray = new address[](memberRoleData[_memberRoleId].memberCounter); for (i = 0; i < length; i++) { address member = memberRoleData[_memberRoleId].memberAddress[i]; if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) { //solhint-disable-line memberArray[j] = member; j++; } } return (_memberRoleId, memberArray); } /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberCounter Member length function numberOfMembers(uint _memberRoleId) public view returns(uint) { //solhint-disable-line return memberRoleData[_memberRoleId].memberCounter; } /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address) { //solhint-disable-line return memberRoleData[_memberRoleId].authorized; } /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory) { //solhint-disable-line uint length = memberRoleData.length; uint[] memory assignedRoles = new uint[](length); uint counter = 0; for (uint i = 1; i < length; i++) { if (memberRoleData[i].memberActive[_memberAddress]) { assignedRoles[counter] = i; counter++; } } return assignedRoles; } /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool) { //solhint-disable-line if (_roleId == uint(Role.UnAssigned)) return true; else if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line return true; else return false; } /// @dev Return total number of members assigned against each role id. /// @return totalMembers Total members in particular role id function getMemberLengthForAllRoles() public view returns(uint[] memory totalMembers) { //solhint-disable-line totalMembers = new uint[](memberRoleData.length); for (uint i = 0; i < memberRoleData.length; i++) { totalMembers[i] = numberOfMembers(i); } } /** * @dev to update the member roles * @param _memberAddress in concern * @param _roleId the id of role * @param _active if active is true, add the member, else remove it */ function _updateRole(address _memberAddress, uint _roleId, bool _active) internal { // require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically"); if (_active) { require(!memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1); memberRoleData[_roleId].memberActive[_memberAddress] = true; memberRoleData[_roleId].memberAddress.push(_memberAddress); } else { require(memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1); delete memberRoleData[_roleId].memberActive[_memberAddress]; } } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function _addRole( bytes32 _roleName, string memory _roleDescription, address _authorized ) internal { emit MemberRole(memberRoleData.length, _roleName, _roleDescription); memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized)); } /** * @dev to check if member is in the given member array * @param _memberAddress in concern * @param memberArray in concern * @return boolean to represent the presence */ function _checkMemberInArray( address _memberAddress, address[] memory memberArray ) internal pure returns(bool memberExists) { uint i; for (i = 0; i < memberArray.length; i++) { if (memberArray[i] == _memberAddress) { memberExists = true; break; } } } /** * @dev to add initial member roles * @param _firstAB is the member address to be added * @param memberAuthority is the member authority(role) to be added for */ function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal { maxABCount = 5; _addRole("Unassigned", "Unassigned", address(0)); _addRole( "Advisory Board", "Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line address(0) ); _addRole( "Member", "Represents all users of Mutual.", //solhint-disable-line memberAuthority ); _addRole( "Owner", "Represents Owner of Mutual.", //solhint-disable-line address(0) ); // _updateRole(_firstAB, uint(Role.AdvisoryBoard), true); _updateRole(_firstAB, uint(Role.Owner), true); // _updateRole(_firstAB, uint(Role.Member), true); launchedOn = 0; } function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) { address memberAddress = memberRoleData[_memberRoleId].memberAddress[index]; return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]); } function membersLength(uint _memberRoleId) external view returns (uint) { return memberRoleData[_memberRoleId].memberAddress.length; } } // File: nexusmutual-contracts/contracts/ProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract ProposalCategory is Governed, IProposalCategory, Iupgradable { bool public constructorCheck; MemberRoles internal mr; struct CategoryStruct { uint memberRoleToVote; uint majorityVotePerc; uint quorumPerc; uint[] allowedToCreateProposal; uint closingTime; uint minStake; } struct CategoryAction { uint defaultIncentive; address contractAddress; bytes2 contractName; } CategoryStruct[] internal allCategory; mapping (uint => CategoryAction) internal categoryActionData; mapping (uint => uint) public categoryABReq; mapping (uint => uint) public isSpecialResolution; mapping (uint => bytes) public categoryActionHashes; bool public categoryActionHashUpdated; /** * @dev Restricts calls to deprecated functions */ modifier deprecated() { revert("Function deprecated"); _; } /** * @dev Adds new category (Discontinued, moved functionality to newCategory) * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external deprecated { } /** * @dev Initiates Default settings for Proposal Category contract (Adding default categories) */ function proposalCategoryInitiate() external deprecated { //solhint-disable-line } /** * @dev Initiates Default action function hashes for existing categories * To be called after the contract has been upgraded by governance */ function updateCategoryActionHashes() external onlyOwner { require(!categoryActionHashUpdated, "Category action hashes already updated"); categoryActionHashUpdated = true; categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)"); categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)"); categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)"); categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()"); categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)"); categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)"); categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)"); categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)"); categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)");//solhint-disable-line categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)"); categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)"); categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)"); categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)"); categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)"); categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)"); categoryActionHashes[29] = abi.encodeWithSignature("upgradeContract(bytes2,address)"); categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)"); categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)"); categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)");//solhint-disable-line categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()"); } /** * @dev Gets Total number of categories added till now */ function totalCategories() external view returns(uint) { return allCategory.length; } /** * @dev Gets category details */ function category(uint _categoryId) external view returns(uint, uint, uint, uint, uint[] memory, uint, uint) { return( _categoryId, allCategory[_categoryId].memberRoleToVote, allCategory[_categoryId].majorityVotePerc, allCategory[_categoryId].quorumPerc, allCategory[_categoryId].allowedToCreateProposal, allCategory[_categoryId].closingTime, allCategory[_categoryId].minStake ); } /** * @dev Gets category ab required and isSpecialResolution * @return the category id * @return if AB voting is required * @return is category a special resolution */ function categoryExtendedData(uint _categoryId) external view returns(uint, uint, uint) { return( _categoryId, categoryABReq[_categoryId], isSpecialResolution[_categoryId] ); } /** * @dev Gets the category acion details * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive */ function categoryAction(uint _categoryId) external view returns(uint, address, bytes2, uint) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); } /** * @dev Gets the category acion details of a category id * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive * @return action function hash */ function categoryActionDetails(uint _categoryId) external view returns(uint, address, bytes2, uint, bytes memory) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive, categoryActionHashes[_categoryId] ); } /** * @dev Updates dependant contract addresses */ function changeDependentContractAddress() public { mr = MemberRoles(ms.getLatestAddress("MR")); } /** * @dev Adds new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function newCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } _addCategory( _name, _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _actionHash, _contractAddress, _contractName, _incentives ); if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash); } } /** * @dev Changes the master address and update it's instance * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev Updates category details (Discontinued, moved functionality to editCategory) * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public deprecated { } /** * @dev Updates category details * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function editCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } delete categoryActionHashes[_categoryId]; if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash); } allCategory[_categoryId].memberRoleToVote = _memberRoleToVote; allCategory[_categoryId].majorityVotePerc = _majorityVotePerc; allCategory[_categoryId].closingTime = _closingTime; allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal; allCategory[_categoryId].minStake = _incentives[0]; allCategory[_categoryId].quorumPerc = _quorumPerc; categoryActionData[_categoryId].defaultIncentive = _incentives[1]; categoryActionData[_categoryId].contractName = _contractName; categoryActionData[_categoryId].contractAddress = _contractAddress; categoryABReq[_categoryId] = _incentives[2]; isSpecialResolution[_categoryId] = _incentives[3]; emit Category(_categoryId, _name, _actionHash); } /** * @dev Internal call to add new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function _addCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) internal { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); allCategory.push( CategoryStruct( _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _incentives[0] ) ); uint categoryId = allCategory.length - 1; categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName); categoryABReq[categoryId] = _incentives[2]; isSpecialResolution[categoryId] = _incentives[3]; emit Category(categoryId, _name, _actionHash); } /** * @dev Internal call to check if given roles are valid or not */ function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal) internal view returns(uint) { uint totalRoles = mr.totalRoles(); if (_memberRoleToVote >= totalRoles) { return 0; } for (uint i = 0; i < _allowedToCreateProposal.length; i++) { if (_allowedToCreateProposal[i] >= totalRoles) { return 0; } } return 1; } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IGovernance.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Edits the details of an existing proposal and creates new version /// @param _proposalId Proposal id that details needs to be updated /// @param _proposalDescHash Proposal description hash having long and short description of proposal. function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Initiates add solution /// @param _solutionHash Solution hash having required data against adding solution function addSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Opens proposal for voting function openProposalForVoting(uint _proposalId) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward); function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns(uint closeValue); function pauseProposal(uint _proposalId) public; function resumeProposal(uint _proposalId) public; function allowedToCatgorize() public view returns(uint roleId); } // File: nexusmutual-contracts/contracts/Governance.sol // /* Copyright (C) 2017 GovBlocks.io // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Governance is IGovernance, Iupgradable { using SafeMath for uint; enum ProposalStatus { Draft, AwaitingSolution, VotingStarted, Accepted, Rejected, Majority_Not_Reached_But_Accepted, Denied } struct ProposalData { uint propStatus; uint finalVerdict; uint category; uint commonIncentive; uint dateUpd; address owner; } struct ProposalVote { address voter; uint proposalId; uint dateAdd; } struct VoteTally { mapping(uint=>uint) memberVoteValue; mapping(uint=>uint) abVoteValue; uint voters; } struct DelegateVote { address follower; address leader; uint lastUpd; } ProposalVote[] internal allVotes; DelegateVote[] public allDelegation; mapping(uint => ProposalData) internal allProposalData; mapping(uint => bytes[]) internal allProposalSolutions; mapping(address => uint[]) internal allVotesByMember; mapping(uint => mapping(address => bool)) public rewardClaimed; mapping (address => mapping(uint => uint)) public memberProposalVote; mapping (address => uint) public followerDelegation; mapping (address => uint) internal followerCount; mapping (address => uint[]) internal leaderDelegation; mapping (uint => VoteTally) public proposalVoteTally; mapping (address => bool) public isOpenForDelegation; mapping (address => uint) public lastRewardClaimed; bool internal constructorCheck; uint public tokenHoldingTime; uint internal roleIdAllowedToCatgorize; uint internal maxVoteWeigthPer; uint internal specialResolutionMajPerc; uint internal maxFollowers; uint internal totalProposals; uint internal maxDraftTime; MemberRoles internal memberRole; ProposalCategory internal proposalCategory; TokenController internal tokenInstance; mapping(uint => uint) public proposalActionStatus; mapping(uint => uint) internal proposalExecutionTime; mapping(uint => mapping(address => bool)) public proposalRejectedByAB; mapping(uint => uint) internal actionRejectedCount; bool internal actionParamsInitialised; uint internal actionWaitingTime; uint constant internal AB_MAJ_TO_REJECT_ACTION = 3; enum ActionStatus { Pending, Accepted, Rejected, Executed, NoAction } /** * @dev Called whenever an action execution is failed. */ event ActionFailed ( uint256 proposalId ); /** * @dev Called whenever an AB member rejects the action execution. */ event ActionRejected ( uint256 indexed proposalId, address rejectedBy ); /** * @dev Checks if msg.sender is proposal owner */ modifier onlyProposalOwner(uint _proposalId) { require(msg.sender == allProposalData[_proposalId].owner, "Not allowed"); _; } /** * @dev Checks if proposal is opened for voting */ modifier voteNotStarted(uint _proposalId) { require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)); _; } /** * @dev Checks if msg.sender is allowed to create proposal under given category */ modifier isAllowed(uint _categoryId) { require(allowedToCreateProposal(_categoryId), "Not allowed"); _; } /** * @dev Checks if msg.sender is allowed categorize proposal under given category */ modifier isAllowedToCategorize() { require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed"); _; } /** * @dev Checks if msg.sender had any pending rewards to be claimed */ modifier checkPendingRewards { require(getPendingReward(msg.sender) == 0, "Claim reward"); _; } /** * @dev Event emitted whenever a proposal is categorized */ event ProposalCategorized( uint indexed proposalId, address indexed categorizedBy, uint categoryId ); /** * @dev Removes delegation of an address. * @param _add address to undelegate. */ function removeDelegation(address _add) external onlyInternal { _unDelegate(_add); } /** * @dev Creates a new proposal * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective */ function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external isAllowed(_categoryId) { require(ms.isMember(msg.sender), "Not Member"); _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); } /** * @dev Edits the details of an existing proposal * @param _proposalId Proposal id that details needs to be updated * @param _proposalDescHash Proposal description hash having long and short description of proposal. */ function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external onlyProposalOwner(_proposalId) { require( allProposalSolutions[_proposalId].length < 2, "Not allowed" ); allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft); allProposalData[_proposalId].category = 0; allProposalData[_proposalId].commonIncentive = 0; emit Proposal( allProposalData[_proposalId].owner, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); } /** * @dev Categorizes proposal to proceed further. Categories shows the proposal objective. */ function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) external voteNotStarted(_proposalId) isAllowedToCategorize { _categorizeProposal(_proposalId, _categoryId, _incentive); } /** * @dev Initiates add solution * To implement the governance interface */ function addSolution(uint, string calldata, bytes calldata) external { } /** * @dev Opens proposal for voting * To implement the governance interface */ function openProposalForVoting(uint) external { } /** * @dev Submit proposal with solution * @param _proposalId Proposal id * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external onlyProposalOwner(_proposalId) { require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution)); _proposalSubmission(_proposalId, _solutionHash, _action); } /** * @dev Creates a new proposal with solution * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external isAllowed(_categoryId) { uint proposalId = totalProposals; _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); require(_categoryId > 0); _proposalSubmission( proposalId, _solutionHash, _action ); } /** * @dev Submit a vote on the proposal. * @param _proposalId to vote upon. * @param _solutionChosen is the chosen vote. */ function submitVote(uint _proposalId, uint _solutionChosen) external { require(allProposalData[_proposalId].propStatus == uint(Governance.ProposalStatus.VotingStarted), "Not allowed"); require(_solutionChosen < allProposalSolutions[_proposalId].length); _submitVote(_proposalId, _solutionChosen); } /** * @dev Closes the proposal. * @param _proposalId of proposal to be closed. */ function closeProposal(uint _proposalId) external { uint category = allProposalData[_proposalId].category; uint _memberRole; if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now && allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } else { require(canCloseProposal(_proposalId) == 1); (, _memberRole, , , , , ) = proposalCategory.category(allProposalData[_proposalId].category); if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) { _closeAdvisoryBoardVote(_proposalId, category); } else { _closeMemberVote(_proposalId, category); } } } /** * @dev Claims reward for member. * @param _memberAddress to claim reward of. * @param _maxRecords maximum number of records to claim reward for. _proposals list of proposals of which reward will be claimed. * @return amount of pending reward. */ function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward) { uint voteId; address leader; uint lastUpd; require(msg.sender == ms.getLatestAddress("CR")); uint delegationId = followerDelegation[_memberAddress]; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; uint totalVotes = allVotesByMember[leader].length; uint lastClaimed = totalVotes; uint j; uint i; for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) { voteId = allVotesByMember[leader][i]; proposalId = allVotes[voteId].proposalId; if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) { if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { if (!rewardClaimed[voteId][_memberAddress]) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); rewardClaimed[voteId][_memberAddress] = true; j++; } } else { if (lastClaimed == totalVotes) { lastClaimed = i; } } } } if (lastClaimed == totalVotes) { lastRewardClaimed[_memberAddress] = i; } else { lastRewardClaimed[_memberAddress] = lastClaimed; } if (j > 0) { emit RewardClaimed( _memberAddress, pendingDAppReward ); } } /** * @dev Sets delegation acceptance status of individual user * @param _status delegation acceptance status */ function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards { isOpenForDelegation[msg.sender] = _status; } /** * @dev Delegates vote to an address. * @param _add is the address to delegate vote to. */ function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards { require(ms.masterInitialized()); require(allDelegation[followerDelegation[_add]].leader == address(0)); if (followerDelegation[msg.sender] > 0) { require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now); } require(!alreadyDelegated(msg.sender)); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner))); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard))); require(followerCount[_add] < maxFollowers); if (allVotesByMember[msg.sender].length > 0) { require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime) < now); } require(ms.isMember(_add)); require(isOpenForDelegation[_add]); allDelegation.push(DelegateVote(msg.sender, _add, now)); followerDelegation[msg.sender] = allDelegation.length - 1; leaderDelegation[_add].push(allDelegation.length - 1); followerCount[_add]++; lastRewardClaimed[msg.sender] = allVotesByMember[_add].length; } /** * @dev Undelegates the sender */ function unDelegate() external isMemberAndcheckPause checkPendingRewards { _unDelegate(msg.sender); } /** * @dev Triggers action of accepted proposal after waiting time is finished */ function triggerAction(uint _proposalId) external { require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger"); _triggerAction(_proposalId, allProposalData[_proposalId].category); } /** * @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious */ function rejectAction(uint _proposalId) external { require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now); require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted)); require(!proposalRejectedByAB[_proposalId][msg.sender]); require( keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category)) != keccak256(abi.encodeWithSignature("swapABMember(address,address)")) ); proposalRejectedByAB[_proposalId][msg.sender] = true; actionRejectedCount[_proposalId]++; emit ActionRejected(_proposalId, msg.sender); if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) { proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected); } } /** * @dev Sets intial actionWaitingTime value * To be called after governance implementation has been updated */ function setInitialActionParameters() external onlyOwner { require(!actionParamsInitialised); actionParamsInitialised = true; actionWaitingTime = 24 * 1 hours; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "GOVHOLD") { val = tokenHoldingTime / (1 days); } else if (code == "MAXFOL") { val = maxFollowers; } else if (code == "MAXDRFT") { val = maxDraftTime / (1 days); } else if (code == "EPTIME") { val = ms.pauseTime() / (1 days); } else if (code == "ACWT") { val = actionWaitingTime / (1 hours); } } /** * @dev Gets all details of a propsal * @param _proposalId whose details we want * @return proposalId * @return category * @return status * @return finalVerdict * @return totalReward */ function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalRewar ) { return( _proposalId, allProposalData[_proposalId].category, allProposalData[_proposalId].propStatus, allProposalData[_proposalId].finalVerdict, allProposalData[_proposalId].commonIncentive ); } /** * @dev Gets some details of a propsal * @param _proposalId whose details we want * @return proposalId * @return number of all proposal solutions * @return amount of votes */ function proposalDetails(uint _proposalId) external view returns(uint, uint, uint) { return( _proposalId, allProposalSolutions[_proposalId].length, proposalVoteTally[_proposalId].voters ); } /** * @dev Gets solution action on a proposal * @param _proposalId whose details we want * @param _solution whose details we want * @return action of a solution on a proposal */ function getSolutionAction(uint _proposalId, uint _solution) external view returns(uint, bytes memory) { return ( _solution, allProposalSolutions[_proposalId][_solution] ); } /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns(uint) { return totalProposals; } /** * @dev Get followers of an address * @return get followers of an address */ function getFollowers(address _add) external view returns(uint[] memory) { return leaderDelegation[_add]; } /** * @dev Gets pending rewards of a member * @param _memberAddress in concern * @return amount of pending reward */ function getPendingReward(address _memberAddress) public view returns(uint pendingDAppReward) { uint delegationId = followerDelegation[_memberAddress]; address leader; uint lastUpd; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) { if (allVotes[allVotesByMember[leader][i]].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) { if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) { proposalId = allVotes[allVotesByMember[leader][i]].proposalId; if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); } } } } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "GOVHOLD") { tokenHoldingTime = val * 1 days; } else if (code == "MAXFOL") { maxFollowers = val; } else if (code == "MAXDRFT") { maxDraftTime = val * 1 days; } else if (code == "EPTIME") { ms.updatePauseTime(val * 1 days); } else if (code == "ACWT") { actionWaitingTime = val * 1 hours; } else { revert("Invalid code"); } } /** * @dev Updates all dependency addresses to latest ones from Master */ function changeDependentContractAddress() public { tokenInstance = TokenController(ms.dAppLocker()); memberRole = MemberRoles(ms.getLatestAddress("MR")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Checks if msg.sender is allowed to create a proposal under given category */ function allowedToCreateProposal(uint category) public view returns(bool check) { if (category == 0) return true; uint[] memory mrAllowed; (, , , , mrAllowed, , ) = proposalCategory.category(category); for (uint i = 0; i < mrAllowed.length; i++) { if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i])) return true; } } /** * @dev Checks if an address is already delegated * @param _add in concern * @return bool value if the address is delegated or not */ function alreadyDelegated(address _add) public view returns(bool delegated) { for (uint i=0; i < leaderDelegation[_add].length; i++) { if (allDelegation[leaderDelegation[_add][i]].leader == _add) { return true; } } } /** * @dev Pauses a proposal * To implement govblocks interface */ function pauseProposal(uint) public { } /** * @dev Resumes a proposal * To implement govblocks interface */ function resumeProposal(uint) public { } /** * @dev Checks If the proposal voting time is up and it's ready to close * i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise! * @param _proposalId Proposal id to which closing value is being checked */ function canCloseProposal(uint _proposalId) public view returns(uint) { uint dateUpdate; uint pStatus; uint _closingTime; uint _roleId; uint majority; pStatus = allProposalData[_proposalId].propStatus; dateUpdate = allProposalData[_proposalId].dateUpd; (, _roleId, majority, , , _closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); if ( pStatus == uint(ProposalStatus.VotingStarted) ) { uint numberOfMembers = memberRole.numberOfMembers(_roleId); if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers || dateUpdate.add(_closingTime) <= now) { return 1; } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters || dateUpdate.add(_closingTime) <= now) return 1; } } else if (pStatus > uint(ProposalStatus.VotingStarted)) { return 2; } else { return 0; } } /** * @dev Gets Id of member role allowed to categorize the proposal * @return roleId allowed to categorize the proposal */ function allowedToCatgorize() public view returns(uint roleId) { return roleIdAllowedToCatgorize; } /** * @dev Gets vote tally data * @param _proposalId in concern * @param _solution of a proposal id * @return member vote value * @return advisory board vote value * @return amount of votes */ function voteTallyData(uint _proposalId, uint _solution) public view returns(uint, uint, uint) { return (proposalVoteTally[_proposalId].memberVoteValue[_solution], proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters); } /** * @dev Internal call to create proposal * @param _proposalTitle of proposal * @param _proposalSD is short description of proposal * @param _proposalDescHash IPFS hash value of propsal * @param _categoryId of proposal */ function _createProposal( string memory _proposalTitle, string memory _proposalSD, string memory _proposalDescHash, uint _categoryId ) internal { require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0); uint _proposalId = totalProposals; allProposalData[_proposalId].owner = msg.sender; allProposalData[_proposalId].dateUpd = now; allProposalSolutions[_proposalId].push(""); totalProposals++; emit Proposal( msg.sender, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); if (_categoryId > 0) _categorizeProposal(_proposalId, _categoryId, 0); } /** * @dev Internal call to categorize a proposal * @param _proposalId of proposal * @param _categoryId of proposal * @param _incentive is commonIncentive */ function _categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) internal { require( _categoryId > 0 && _categoryId < proposalCategory.totalCategories(), "Invalid category" ); allProposalData[_proposalId].category = _categoryId; allProposalData[_proposalId].commonIncentive = _incentive; allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution); emit ProposalCategorized(_proposalId, msg.sender, _categoryId); } /** * @dev Internal call to add solution to a proposal * @param _proposalId in concern * @param _action on that solution * @param _solutionHash string value */ function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash) internal { allProposalSolutions[_proposalId].push(_action); emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now); } /** * @dev Internal call to add solution and open proposal for voting */ function _proposalSubmission( uint _proposalId, string memory _solutionHash, bytes memory _action ) internal { uint _categoryId = allProposalData[_proposalId].category; if (proposalCategory.categoryActionHashes(_categoryId).length == 0) { require(keccak256(_action) == keccak256("")); proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } _addSolution( _proposalId, _action, _solutionHash ); _updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted)); (, , , , , uint closingTime, ) = proposalCategory.category(_categoryId); emit CloseProposalOnTime(_proposalId, closingTime.add(now)); } /** * @dev Internal call to submit vote * @param _proposalId of proposal in concern * @param _solution for that proposal */ function _submitVote(uint _proposalId, uint _solution) internal { uint delegationId = followerDelegation[msg.sender]; uint mrSequence; uint majority; uint closingTime; (, mrSequence, majority, , , closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed"); require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed"); require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) && _checkLastUpd(allDelegation[delegationId].lastUpd))); require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized"); uint totalVotes = allVotes.length; allVotesByMember[msg.sender].push(totalVotes); memberProposalVote[msg.sender][_proposalId] = totalVotes; allVotes.push(ProposalVote(msg.sender, _proposalId, now)); emit Vote(msg.sender, _proposalId, totalVotes, now, _solution); if (mrSequence == uint(MemberRoles.Role.Owner)) { if (_solution == 1) _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner); else _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } else { uint numberOfMembers = memberRole.numberOfMembers(mrSequence); _setVoteTally(_proposalId, _solution, mrSequence); if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) { emit VoteCast(_proposalId); } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters) emit VoteCast(_proposalId); } } } /** * @dev Internal call to set vote tally of a proposal * @param _proposalId of proposal in concern * @param _solution of proposal in concern * @param mrSequence number of members for a role */ function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal { uint categoryABReq; uint isSpecialResolution; (, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category); if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) || mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { proposalVoteTally[_proposalId].abVoteValue[_solution]++; } tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime); if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) { uint voteWeight; uint voters = 1; uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender); uint totalSupply = tokenInstance.totalSupply(); if (isSpecialResolution == 1) { voteWeight = tokenBalance.add(10**18); } else { voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18); } DelegateVote memory delegationData; for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) { delegationData = allDelegation[leaderDelegation[msg.sender][i]]; if (delegationData.leader == msg.sender && _checkLastUpd(delegationData.lastUpd)) { if (memberRole.checkRole(delegationData.follower, mrSequence)) { tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower); tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime); voters++; if (isSpecialResolution == 1) { voteWeight = voteWeight.add(tokenBalance.add(10**18)); } else { voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18)); } } } } proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight); proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters; } } /** * @dev Gets minimum of two numbers * @param a one of the two numbers * @param b one of the two numbers * @return minimum number out of the two */ function _minOf(uint a, uint b) internal pure returns(uint res) { res = a; if (res > b) res = b; } /** * @dev Check the time since last update has exceeded token holding time or not * @param _lastUpd is last update time * @return the bool which tells if the time since last update has exceeded token holding time or not */ function _checkLastUpd(uint _lastUpd) internal view returns(bool) { return (now - _lastUpd) > tokenHoldingTime; } /** * @dev Checks if the vote count against any solution passes the threshold value or not. */ function _checkForThreshold(uint _proposalId, uint _category) internal view returns(bool check) { uint categoryQuorumPerc; uint roleAuthorized; (, roleAuthorized, , categoryQuorumPerc, , , ) = proposalCategory.category(_category); check = ((proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1])) .mul(100)) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18) ) ) >= categoryQuorumPerc; } /** * @dev Called when vote majority is reached * @param _proposalId of proposal in concern * @param _status of proposal in concern * @param category of proposal in concern * @param max vote value of proposal in concern */ function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal { allProposalData[_proposalId].finalVerdict = max; _updateProposalStatus(_proposalId, _status); emit ProposalAccepted(_proposalId); if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) { if (role == MemberRoles.Role.AdvisoryBoard) { _triggerAction(_proposalId, category); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); proposalExecutionTime[_proposalId] = actionWaitingTime.add(now); } } } /** * @dev Internal function to trigger action of accepted proposal */ function _triggerAction(uint _proposalId, uint _categoryId) internal { proposalActionStatus[_proposalId] = uint(ActionStatus.Executed); bytes2 contractName; address actionAddress; bytes memory _functionHash; (, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId); if (contractName == "MS") { actionAddress = address(ms); } else if (contractName != "EX") { actionAddress = ms.getLatestAddress(contractName); } (bool actionStatus, ) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1])); if (actionStatus) { emit ActionSuccess(_proposalId); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); emit ActionFailed(_proposalId); } } /** * @dev Internal call to update proposal status * @param _proposalId of proposal in concern * @param _status of proposal to set */ function _updateProposalStatus(uint _proposalId, uint _status) internal { if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) { proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } allProposalData[_proposalId].dateUpd = now; allProposalData[_proposalId].propStatus = _status; } /** * @dev Internal call to undelegate a follower * @param _follower is address of follower to undelegate */ function _unDelegate(address _follower) internal { uint followerId = followerDelegation[_follower]; if (followerId > 0) { followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1); allDelegation[followerId].leader = address(0); allDelegation[followerId].lastUpd = now; lastRewardClaimed[_follower] = allVotesByMember[_follower].length; } } /** * @dev Internal call to close member voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeMemberVote(uint _proposalId, uint category) internal { uint isSpecialResolution; uint abMaj; (, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category); if (isSpecialResolution == 1) { uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10**18) )); if (acceptedVotePerc >= specialResolutionMajPerc) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } else { if (_checkForThreshold(_proposalId, category)) { uint majorityVote; (, , majorityVote, , , , ) = proposalCategory.category(category); if ( ((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)) .div(proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1]) )) >= majorityVote ) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } } else { if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } if (proposalVoteTally[_proposalId].voters > 0) { tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive); } } /** * @dev Internal call to close advisory board voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard; (, , _majorityVote, , , , ) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } }
to change the capacity limit val is the new value/
function _changeCapacityLimit(uint val) internal { capacityLimit = val; }
7,286,877
./partial_match/1/0xa202D5B0892f2981bA86C981884cebA49B8AE096/sources/DigitalaxGenesisStaking.sol
Getter functions for Staking contract Get the tokens staked by a user
function getStakedTokens( address _user ) external view returns (uint256[] memory tokenIds) { return stakers[_user].tokenIds; }
2,671,384
pragma solidity ^ 0.5.17; import "./SafeMath.sol"; import "./Iupgradable.sol"; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); if (_vote == -1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); if (_vote == -1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns(uint voteCount) { return allvotes.length.sub(1); //Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns(uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns(address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns(uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns(uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns(address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns(uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns(uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns(uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns(uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns(uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns(uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns(uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns(int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns(uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns(uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); //0 Pending-Claim Assessor Vote _pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); //12 Claim Accepted Payout Pending _pushStatus(0, 0); //13 Claim Accepted No Payout _pushStatus(0, 0); //14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */
Gets the verdict of a vote using claim id and index. _ca 1 for vote given as a CA, else for vote given as a member. return ver 1 if vote was given in favour,-1 if given in against./
function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; }
5,407,143
./full_match/5/0x5c903Ed768B7D3Cc57f84c43c7efCb4a9Ff1BAD4/sources/contracts/EthWager.sol
Function to place a wager for a specific game and seat
function placeWager(uint256 gameId, string memory seatDirection) external payable { require(gameStarted[gameId], "Game has not started"); SeatDirection seat = parseSeatDirection(seatDirection); uint256 seatId = uint256(seat); require(seatId < TOTAL_SEATS, "Invalid seat direction"); require(msg.value == 1e16, "Must wager exactly 0.01 ETH"); require(players[gameId][seatId] == address(0), "Seat already taken"); wagers[gameId][seatId] = msg.value; players[gameId][seatId] = msg.sender; emit WagerPlaced(gameId, seatId, msg.sender, msg.value); }
11,586,109
/** *Submitted for verification at Etherscan.io on 2021-08-24 */ // SPDX-License-Identifier: UNLICENCED pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/utils/structs/EnumerableSet.sol pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/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 { 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 {} } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/security/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/token/ERC721/extensions/ERC721Pausable.sol pragma solidity ^0.8.0; /** * @dev ERC721 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 ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/token/ERC721/extensions/ERC721Burnable.sol pragma solidity ^0.8.0; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/access/IAccessControl.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/access/AccessControl.sol pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/access/IAccessControlEnumerable.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/access/AccessControlEnumerable.sol pragma solidity ^0.8.0; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 override returns (address) { return _roleMembers[role].at(index); } /** * @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 override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol pragma solidity ^0.8.0; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC721PresetMinterPauserAutoId is Context, AccessControlEnumerable, ERC721Enumerable, ERC721Burnable, ERC721Pausable { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); Counters.Counter private _tokenIdTracker; string private _baseTokenURI; uint8 private constant MAX_URI_RESETS_ALLOWED = 1; uint8 public uriResetCount = 0; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ constructor( string memory name, string memory symbol ) ERC721(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Sets `_baseTokenURI` * Resets allowed only `MAX_URI_RESETS_ALLOWED` no of times **/ function setBaseURI(string memory baseTokenURI) public { require(hasRole(MINTER_ROLE, _msgSender()), "You don't have permission to do this."); require(uriResetCount <= MAX_URI_RESETS_ALLOWED, "Max resets allowed is breached now"); _baseTokenURI = baseTokenURI; uriResetCount++; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()); _tokenIdTracker.increment(); } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } contract GiraffeX is ERC721PresetMinterPauserAutoId { using Strings for uint256; uint16 public maxSupply = 3333; uint256 public price = 60000000000000000; // start at 0.06 ETH uint256 public discountFactor = 5000000000000000; // start at 0.005 ETH address payable account1 = payable(0x769BDabd37c16dE9c2e856991B9c0B8AFbcB77db); // payout account using Counters for Counters.Counter; Counters.Counter private _tokenIds; constructor() ERC721PresetMinterPauserAutoId("GiraffeX", "GX") { _tokenIds.increment(); } function changePrice(uint256 _price) public { require(hasRole(MINTER_ROLE, _msgSender()), "You don't have permission to do this."); price = _price; } function changeDiscountFactor(uint256 _df) public { require(hasRole(MINTER_ROLE, _msgSender()), "You don't have permission to do this."); require(discountFactor < price, "discountFactor should be less than price"); discountFactor = _df; } function buy(uint pack) payable external { // enforce supply limit uint256 totalMinted = totalSupply(); require(totalMinted < maxSupply, "Sold out."); // single if (pack == 0) { require(msg.value >= price, "Not enough ETH."); mintNFT(1); } // 5x-pack else if (pack == 1) { require(msg.value >= (price - discountFactor) * 5, "Not enough ETH. "); mintNFT(5); } // 10x-pack else if (pack == 2) { require(msg.value >= (price - (2 * discountFactor)) * 10, "Not enough ETH."); mintNFT(10); } // 20x-pack else if (pack == 3) { require(msg.value >= (price - (2 * discountFactor)) * 20, "Not enough ETH."); mintNFT(20); } } function mintNFT(uint16 amount) private { for (uint i = 0; i < amount; i++) { _mint(msg.sender, _tokenIds.current()); _tokenIds.increment(); } } 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(), ".json")) : ""; } // send contract balance to payout address function payAccounts() public payable { uint256 balance = address(this).balance; if (balance != 0) { account1.transfer((balance)); } } }
send contract balance to payout address
function payAccounts() public payable { uint256 balance = address(this).balance; if (balance != 0) { account1.transfer((balance)); } }
10,976,420
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import './Storage.sol'; contract Royalties is Initializable, OwnableUpgradeable, Storage { /* Inits Contract */ function __Royalties_init( address __royaltiesReceiver, uint256 royaltiesPercentage ) internal initializer { __Ownable_init(); setRoyaltiesReceiver(__royaltiesReceiver); setRoyalties(royaltiesPercentage); } function royaltyInfo(uint256 _nftId, uint256 _salePrice) external view returns ( address receiver, uint256 royaltyAmount, uint256 tokenId ) { return ( _royaltiesReceiver, _salePrice * (_royaltiesPercentage / 100), _nftId ); } /// @notice Changes the royalties' recipient address (in case rights are /// transferred for instance) /// @param newRoyaltiesReceiver - address of the new royalties recipient function setRoyaltiesReceiver(address newRoyaltiesReceiver) public onlyOwner { require(newRoyaltiesReceiver != _royaltiesReceiver); // dev: Same address _royaltiesReceiver = newRoyaltiesReceiver; } /// @notice Changes the royalties' percentage of contract /// @param newRoyalties - address of the new royalties recipient function setRoyalties(uint256 newRoyalties) public onlyOwner { require(newRoyalties != _royaltiesPercentage); // dev: Same address _royaltiesPercentage = newRoyalties; } }
Changes the royalties' percentage of contract newRoyalties - address of the new royalties recipient
function setRoyalties(uint256 newRoyalties) public onlyOwner { _royaltiesPercentage = newRoyalties; }
13,092,432
./full_match/3/0x2D192d0b0581a85Fe873489D63f3bb4c2f8758F1/sources/Module.sol
Returns whether the module implements a callback for a given static call method. _methodId The method id./
function supportsStaticCall(bytes4 _methodId) external view returns (bool _isSupported) { return false; }
8,116,814
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; import "./SafeERC20.sol"; import "./Ownable.sol"; import "./IERC677.sol"; import "./ISweeper.sol"; /** * @title Keep3rSweeper * @dev Handles withdrawing of node rewards from Chainlink contracts. */ contract Keep3rSweeper is Ownable { using SafeMath for uint256; using SafeERC20 for IERC677; address[] public sweepers; address public rewardsWallet; IERC677 public rewardsToken; uint256 public minRewardsForPayment; uint256 public batchSize; event Withdraw(address indexed sender, uint256 amount); constructor( address _rewardsToken, address _rewardsWallet, uint256 _minRewardsForPayment, uint256 _batchSize ) { rewardsToken = IERC677(_rewardsToken); rewardsWallet = _rewardsWallet; minRewardsForPayment = _minRewardsForPayment; batchSize = _batchSize; } /** * @dev returns whether or not rewards should be withdrawn and the indexes to withdraw from * @return whether to perform upkeep and calldata to use **/ function checkUpkeep(bytes calldata _checkData) external view returns (bool, bytes memory) { uint256[][] memory performData = new uint256[][](sweepers.length); uint256 totalRewards; uint256 batch = 0; for (uint i = 0; i < sweepers.length && batch < batchSize; i++) { ISweeper sweeper = ISweeper(sweepers[i]); uint256 minToWithdraw = sweeper.minToWithdraw(); uint256[] memory canWithdraw = sweeper.withdrawable(); uint256 canWithdrawCount; for (uint j = 0; j < canWithdraw.length && batch < batchSize; j++) { if (canWithdraw[j] >= minToWithdraw) { canWithdrawCount++; batch++; } } performData[i] = new uint256[](canWithdrawCount); uint256 addedCount; for (uint j = 0; j < canWithdraw.length && addedCount < canWithdrawCount; j++) { if (canWithdraw[j] >= minToWithdraw) { totalRewards = totalRewards.add(canWithdraw[j]); performData[i][addedCount++] = j; } } } return (totalRewards >= minRewardsForPayment, abi.encode(performData)); } /** * @dev withdraw rewards for selected contracts if rewards >= minRewardsForPayment * @param _performData indexes of the contracts **/ function performUpkeep(bytes calldata _performData) external { _withdraw(_performData); uint256 rewards = rewardsToken.balanceOf(address(this)); require(rewards >= minRewardsForPayment, "Rewards must be >= minRewardsForPayment"); rewardsToken.transferAndCall(rewardsWallet, rewards, "0x00"); emit Withdraw(msg.sender, rewards); } /** * @dev withdraw rewards for selected contracts * @param _sweeperIdxs indexes of the contracts **/ function withdraw(uint256[][] calldata _sweeperIdxs) external { _withdraw(abi.encode(_sweeperIdxs)); uint256 rewards = rewardsToken.balanceOf(address(this)); require(rewards > 0, "Rewards must be > 0"); rewardsToken.transferAndCall(rewardsWallet, rewards, "0x00"); emit Withdraw(msg.sender, rewards); } /** * @dev withdrawable amount from oracles * @return total withdrawable balance **/ function withdrawable() external view returns (uint256[][] memory) { uint256[][] memory _withdrawable = new uint256[][](sweepers.length); for (uint i = 0; i < sweepers.length; i++) { _withdrawable[i] = ISweeper(sweepers[i]).withdrawable(); } return _withdrawable; } /** * @dev adds sweeper address * @param _sweeper address to add **/ function addSweeper(address _sweeper) external onlyOwner() { sweepers.push(_sweeper); } /** * @dev removes sweeper address * @param _index index of sweeper to remove **/ function removeSweeper(uint256 _index) external onlyOwner() { require(_index < sweepers.length, "Sweeper does not exist"); sweepers[_index] = sweepers[sweepers.length - 1]; delete sweepers[sweepers.length - 1]; } /** * @dev sets minimum amount of rewards needed to receive payment on withdraw * @param _minRewardsForPayment amount to set **/ function setMinRewardsForPayment(uint256 _minRewardsForPayment) external onlyOwner() { minRewardsForPayment = _minRewardsForPayment; } /** * @dev sets maximum batch size for withdrawals * @param _batchSize amount to set **/ function setBatchSize(uint256 _batchSize) external onlyOwner() { batchSize = _batchSize; } /** * @dev withdraw rewards for selected contracts * @param _sweeperIdxs indexes of the contracts **/ function _withdraw(bytes memory _sweeperIdxs) private { uint256[][] memory sweeperIdxs = abi.decode(_sweeperIdxs, (uint256[][])); require(sweeperIdxs.length <= sweepers.length, "SweeperIdxs must be <= sweepers length"); for (uint i = 0; i < sweeperIdxs.length; i++) { if (sweeperIdxs[i].length > 0) { ISweeper(sweepers[i]).withdraw(sweeperIdxs[i]); } } } }
withdraw rewards for selected contracts _sweeperIdxs indexes of the contracts/
function _withdraw(bytes memory _sweeperIdxs) private { uint256[][] memory sweeperIdxs = abi.decode(_sweeperIdxs, (uint256[][])); require(sweeperIdxs.length <= sweepers.length, "SweeperIdxs must be <= sweepers length"); for (uint i = 0; i < sweeperIdxs.length; i++) { if (sweeperIdxs[i].length > 0) { ISweeper(sweepers[i]).withdraw(sweeperIdxs[i]); } } }
5,889,947
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./AMM.sol"; import "../lib/CappedPool.sol"; import "../lib/CombinedActionsGuard.sol"; import "../interfaces/IPriceProvider.sol"; import "../interfaces/IIVProvider.sol"; import "../interfaces/IBlackScholes.sol"; import "../interfaces/IIVGuesser.sol"; import "../interfaces/IPodOption.sol"; import "../interfaces/IOptionAMMPool.sol"; import "../interfaces/IFeePool.sol"; import "../interfaces/IConfigurationManager.sol"; import "../interfaces/IEmergencyStop.sol"; import "../interfaces/IFeePoolBuilder.sol"; import "../options/rewards/AaveIncentives.sol"; /** * Represents an Option specific single-sided AMM. * * The tokenA MUST be an PodOption contract implementation. * The tokenB is preferable to be an stable asset such as DAI or USDC. * * There are 4 external contracts used by this contract: * * - priceProvider: responsible for the the spot price of the option's underlying asset. * - priceMethod: responsible for the current price of the option itself. * - impliedVolatility: responsible for one of the priceMethod inputs: * implied Volatility * - feePoolA and feePoolB: responsible for handling Liquidity providers fees. */ contract OptionAMMPool is AMM, IOptionAMMPool, CappedPool, CombinedActionsGuard, ReentrancyGuard, AaveIncentives { using SafeMath for uint256; uint256 public constant PRICING_DECIMALS = 18; uint256 private constant _SECONDS_IN_A_YEAR = 31536000; uint256 private constant _ORACLE_IV_WEIGHT = 3; uint256 private constant _POOL_IV_WEIGHT = 1; // External Contracts /** * @notice store globally accessed configurations */ IConfigurationManager public immutable configurationManager; /** * @notice responsible for handling Liquidity providers fees of the token A */ IFeePool public immutable feePoolA; /** * @notice responsible for handling Liquidity providers fees of the token B */ IFeePool public immutable feePoolB; // Option Info struct PriceProperties { uint256 expiration; uint256 startOfExerciseWindow; uint256 strikePrice; address underlyingAsset; IPodOption.OptionType optionType; uint256 currentIV; int256 riskFree; uint256 initialIVGuess; } /** * @notice priceProperties are all information needed to handle the price discovery method * most of the properties will be used by getABPrice */ PriceProperties public priceProperties; event TradeInfo(uint256 spotPrice, uint256 newIV); constructor( address _optionAddress, address _stableAsset, uint256 _initialIV, IConfigurationManager _configurationManager, IFeePoolBuilder _feePoolBuilder ) public AMM(_optionAddress, _stableAsset) CappedPool(_configurationManager) AaveIncentives(_configurationManager) { require( IPodOption(_optionAddress).exerciseType() == IPodOption.ExerciseType.EUROPEAN, "Pool: invalid exercise type" ); feePoolA = _feePoolBuilder.buildFeePool(_stableAsset, 10, 3, address(this)); feePoolB = _feePoolBuilder.buildFeePool(_stableAsset, 10, 3, address(this)); priceProperties.currentIV = _initialIV; priceProperties.initialIVGuess = _initialIV; priceProperties.underlyingAsset = IPodOption(_optionAddress).underlyingAsset(); priceProperties.expiration = IPodOption(_optionAddress).expiration(); priceProperties.startOfExerciseWindow = IPodOption(_optionAddress).startOfExerciseWindow(); priceProperties.optionType = IPodOption(_optionAddress).optionType(); uint256 strikePrice = IPodOption(_optionAddress).strikePrice(); uint256 strikePriceDecimals = IPodOption(_optionAddress).strikePriceDecimals(); require(strikePriceDecimals <= PRICING_DECIMALS, "Pool: invalid strikePrice unit"); require(tokenBDecimals() <= PRICING_DECIMALS, "Pool: invalid tokenB unit"); uint256 strikePriceWithRightDecimals = strikePrice.mul(10**(PRICING_DECIMALS - strikePriceDecimals)); priceProperties.strikePrice = strikePriceWithRightDecimals; configurationManager = IConfigurationManager(_configurationManager); } /** * @notice addLiquidity in any proportion of tokenA or tokenB * * @dev This function can only be called before option expiration * * @param amountOfA amount of TokenA to add * @param amountOfB amount of TokenB to add * @param owner address of the account that will have ownership of the liquidity */ function addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner ) external override capped(tokenB(), amountOfB) { require(msg.sender == configurationManager.getOptionHelper() || msg.sender == owner, "AMM: invalid sender"); _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); _addLiquidity(amountOfA, amountOfB, owner); _emitTradeInfo(); } /** * @notice removeLiquidity in any proportion of tokenA or tokenB * * @param amountOfA amount of TokenA to add * @param amountOfB amount of TokenB to add */ function removeLiquidity(uint256 amountOfA, uint256 amountOfB) external override nonReentrant { _nonCombinedActions(); _emergencyStopCheck(); _removeLiquidity(amountOfA, amountOfB); _emitTradeInfo(); } /** * @notice withdrawRewards claims reward from Aave and send to admin * @dev should only be called by the admin power * */ function withdrawRewards() external override { require(msg.sender == configurationManager.owner(), "not owner"); address[] memory assets = new address[](1); assets[0] = this.tokenB(); _claimRewards(assets); address rewardAsset = _parseAddressFromUint(configurationManager.getParameter("REWARD_ASSET")); uint256 rewardsToSend = _rewardBalance(); IERC20(rewardAsset).safeTransfer(msg.sender, rewardsToSend); } /** * @notice tradeExactAInput msg.sender is able to trade exact amount of token A in exchange for minimum * amount of token B and send the tokens B to the owner. After that, this function also updates the * priceProperties.* currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result in less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactAInput first. * * @param exactAmountAIn exact amount of A token that will be transfer from msg.sender * @param minAmountBOut minimum acceptable amount of token B to transfer to owner * @param owner the destination address that will receive the token B * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactAInput( uint256 exactAmountAIn, uint256 minAmountBOut, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountBOut = _tradeExactAInput(exactAmountAIn, minAmountBOut, owner); _emitTradeInfo(); return amountBOut; } /** * @notice _tradeExactAOutput owner is able to receive exact amount of token A in exchange of a max * acceptable amount of token B transfer from the msg.sender. After that, this function also updates * the priceProperties.currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result in less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactAOutput first. * * @param exactAmountAOut exact amount of token A that will be transfer to owner * @param maxAmountBIn maximum acceptable amount of token B to transfer from msg.sender * @param owner the destination address that will receive the token A * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountBIn = _tradeExactAOutput(exactAmountAOut, maxAmountBIn, owner); _emitTradeInfo(); return amountBIn; } /** * @notice _tradeExactBInput msg.sender is able to trade exact amount of token B in exchange for minimum * amount of token A sent to the owner. After that, this function also updates the priceProperties.currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result ini less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactBInput first. * * @param exactAmountBIn exact amount of token B that will be transfer from msg.sender * @param minAmountAOut minimum acceptable amount of token A to transfer to owner * @param owner the destination address that will receive the token A * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactBInput( uint256 exactAmountBIn, uint256 minAmountAOut, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountAOut = _tradeExactBInput(exactAmountBIn, minAmountAOut, owner); _emitTradeInfo(); return amountAOut; } /** * @notice _tradeExactBOutput owner is able to receive exact amount of token B in exchange of a max * acceptable amount of token A transfer from msg.sender. After that, this function also updates the * priceProperties.currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result ini less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactBOutput first. * * @param exactAmountBOut exact amount of token B that will be transfer to owner * @param maxAmountAIn maximum acceptable amount of token A to transfer from msg.sender * @param owner the destination address that will receive the token B * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactBOutput( uint256 exactAmountBOut, uint256 maxAmountAIn, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountAIn = _tradeExactBOutput(exactAmountBOut, maxAmountAIn, owner); _emitTradeInfo(); return amountAIn; } /** * @notice getRemoveLiquidityAmounts external function that returns the available for rescue * amounts of token A, and token B based on the original position * * @param percentA percent of exposition of Token A to be removed * @param percentB percent of exposition of Token B to be removed * @param user Opening Value Factor by the moment of the deposit * * @return withdrawAmountA the total amount of token A that will be rescued * @return withdrawAmountB the total amount of token B that will be rescued plus fees */ function getRemoveLiquidityAmounts( uint256 percentA, uint256 percentB, address user ) external override view returns (uint256 withdrawAmountA, uint256 withdrawAmountB) { (uint256 poolWithdrawAmountA, uint256 poolWithdrawAmountB) = _getRemoveLiquidityAmounts( percentA, percentB, user ); (uint256 feeSharesA, uint256 feeSharesB) = _getAmountOfFeeShares(percentA, percentB, user); uint256 feesWithdrawAmountA = 0; uint256 feesWithdrawAmountB = 0; if (feeSharesA > 0) { (, feesWithdrawAmountA) = feePoolA.getWithdrawAmount(user, feeSharesA); } if (feeSharesB > 0) { (, feesWithdrawAmountB) = feePoolB.getWithdrawAmount(user, feeSharesB); } withdrawAmountA = poolWithdrawAmountA; withdrawAmountB = poolWithdrawAmountB.add(feesWithdrawAmountA).add(feesWithdrawAmountB); return (withdrawAmountA, withdrawAmountB); } /** * @notice getABPrice This function wll call internal function _getABPrice that will calculate the * calculate the ABPrice based on current market conditions. It calculates only the unit price AB, not taking in * consideration the slippage. * * @return ABPrice ABPrice is the unit price AB. Meaning how many units of B, buys 1 unit of A */ function getABPrice() external override view returns (uint256 ABPrice) { return _getABPrice(); } /** * @notice getAdjustedIV This function will return the adjustedIV, which is an average * between the pool IV and an external oracle IV * * @return adjustedIV The average between pool's IV and external oracle IV */ function getAdjustedIV() external override view returns (uint256 adjustedIV) { return _getAdjustedIV(tokenA(), priceProperties.currentIV); } /** * @notice getOptionTradeDetailsExactAInput view function that simulates a trade, in order the preview * the amountBOut, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountAIn amount of token A that will by transfer from msg.sender to the pool * * @return amountBOut amount of B in exchange of the exactAmountAIn * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactAInput(uint256 exactAmountAIn) external override view returns ( uint256 amountBOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactAInput(exactAmountAIn); } /** * @notice getOptionTradeDetailsExactAOutput view function that simulates a trade, in order the preview * the amountBIn, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountAOut amount of token A that will by transfer from pool to the msg.sender/owner * * @return amountBIn amount of B that will be transfer from msg.sender to the pool * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactAOutput(uint256 exactAmountAOut) external override view returns ( uint256 amountBIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactAOutput(exactAmountAOut); } /** * @notice getOptionTradeDetailsExactBInput view function that simulates a trade, in order the preview * the amountAOut, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountBIn amount of token B that will by transfer from msg.sender to the pool * * @return amountAOut amount of A that will be transfer from contract to owner * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactBInput(uint256 exactAmountBIn) external override view returns ( uint256 amountAOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactBInput(exactAmountBIn); } /** * @notice getOptionTradeDetailsExactBOutput view function that simulates a trade, in order the preview * the amountAIn, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountBOut amount of token B that will by transfer from pool to the msg.sender/owner * * @return amountAIn amount of A that will be transfer from msg.sender to the pool * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactBOutput(uint256 exactAmountBOut) external override view returns ( uint256 amountAIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactBOutput(exactAmountBOut); } function _getOptionTradeDetailsExactAInput(uint256 exactAmountAIn) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 amountBOutPool = _getAmountBOutPool(exactAmountAIn, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, exactAmountAIn, amountBOutPool, TradeDirection.AB); // Prevents the pool to sell an option under the minimum target price, // because it causes an infinite loop when trying to calculate newIV if (!_isValidTargetPrice(newTargetABPrice, spotPrice)) { return (0, 0, 0, 0); } uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); uint256 feesTokenA = feePoolA.getCollectable(amountBOutPool, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(amountBOutPool, poolAmountB); uint256 amountBOutUser = amountBOutPool.sub(feesTokenA).sub(feesTokenB); return (amountBOutUser, newIV, feesTokenA, feesTokenB); } function _getOptionTradeDetailsExactAOutput(uint256 exactAmountAOut) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 amountBInPool = _getAmountBInPool(exactAmountAOut, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, exactAmountAOut, amountBInPool, TradeDirection.BA); uint256 feesTokenA = feePoolA.getCollectable(amountBInPool, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(amountBInPool, poolAmountB); uint256 amountBInUser = amountBInPool.add(feesTokenA).add(feesTokenB); uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); return (amountBInUser, newIV, feesTokenA, feesTokenB); } function _getOptionTradeDetailsExactBInput(uint256 exactAmountBIn) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 feesTokenA = feePoolA.getCollectable(exactAmountBIn, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(exactAmountBIn, poolAmountB); uint256 totalFees = feesTokenA.add(feesTokenB); uint256 poolBIn = exactAmountBIn.sub(totalFees); uint256 amountAOutPool = _getAmountAOutPool(poolBIn, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, amountAOutPool, poolBIn, TradeDirection.BA); uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); return (amountAOutPool, newIV, feesTokenA, feesTokenB); } function _getOptionTradeDetailsExactBOutput(uint256 exactAmountBOut) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 feesTokenA = feePoolA.getCollectable(exactAmountBOut, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(exactAmountBOut, poolAmountB); uint256 totalFees = feesTokenA.add(feesTokenB); uint256 poolBOut = exactAmountBOut.add(totalFees); uint256 amountAInPool = _getAmountAInPool(poolBOut, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, amountAInPool, poolBOut, TradeDirection.AB); // Prevents the pool to sell an option under the minimum target price, // because it causes an infinite loop when trying to calculate newIV if (!_isValidTargetPrice(newTargetABPrice, spotPrice)) { return (0, 0, 0, 0); } uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); return (amountAInPool, newIV, feesTokenA, feesTokenB); } function _getPriceDetails() internal view returns ( uint256, uint256, uint256 ) { uint256 timeToMaturity = _getTimeToMaturityInYears(); if (timeToMaturity == 0) { return (0, 0, 0); } uint256 spotPrice = _getSpotPrice(priceProperties.underlyingAsset, PRICING_DECIMALS); uint256 adjustedIV = _getAdjustedIV(tokenA(), priceProperties.currentIV); IBlackScholes pricingMethod = IBlackScholes(configurationManager.getPricingMethod()); uint256 newABPrice; if (priceProperties.optionType == IPodOption.OptionType.PUT) { newABPrice = pricingMethod.getPutPrice( spotPrice, priceProperties.strikePrice, adjustedIV, timeToMaturity, priceProperties.riskFree ); } else { newABPrice = pricingMethod.getCallPrice( spotPrice, priceProperties.strikePrice, adjustedIV, timeToMaturity, priceProperties.riskFree ); } if (newABPrice == 0) { return (0, spotPrice, timeToMaturity); } uint256 newABPriceWithDecimals = newABPrice.div(10**(PRICING_DECIMALS.sub(tokenBDecimals()))); return (newABPriceWithDecimals, spotPrice, timeToMaturity); } /** * @dev returns maturity in years with 18 decimals */ function _getTimeToMaturityInYears() internal view returns (uint256) { if (block.timestamp >= priceProperties.expiration) { return 0; } return priceProperties.expiration.sub(block.timestamp).mul(10**PRICING_DECIMALS).div(_SECONDS_IN_A_YEAR); } function _getPoolAmounts(uint256 newABPrice) internal view returns (uint256 poolAmountA, uint256 poolAmountB) { (uint256 totalAmountA, uint256 totalAmountB) = _getPoolBalances(); if (newABPrice != 0) { poolAmountA = _min(totalAmountA, totalAmountB.mul(10**uint256(tokenADecimals())).div(newABPrice)); poolAmountB = _min(totalAmountB, totalAmountA.mul(newABPrice).div(10**uint256(tokenADecimals()))); } return (poolAmountA, poolAmountB); } function _getABPrice() internal override view returns (uint256) { (uint256 newABPrice, , ) = _getPriceDetails(); return newABPrice; } function _getSpotPrice(address asset, uint256 decimalsOutput) internal view returns (uint256) { IPriceProvider priceProvider = IPriceProvider(configurationManager.getPriceProvider()); uint256 spotPrice = priceProvider.getAssetPrice(asset); uint256 spotPriceDecimals = priceProvider.getAssetDecimals(asset); uint256 diffDecimals; uint256 spotPriceWithRightPrecision; if (decimalsOutput <= spotPriceDecimals) { diffDecimals = spotPriceDecimals.sub(decimalsOutput); spotPriceWithRightPrecision = spotPrice.div(10**diffDecimals); } else { diffDecimals = decimalsOutput.sub(spotPriceDecimals); spotPriceWithRightPrecision = spotPrice.mul(10**diffDecimals); } return spotPriceWithRightPrecision; } function _getOracleIV(address optionAddress) internal view returns (uint256 normalizedOracleIV) { IIVProvider ivProvider = IIVProvider(configurationManager.getIVProvider()); (, , uint256 oracleIV, uint256 ivDecimals) = ivProvider.getIV(optionAddress); uint256 diffDecimals; if (ivDecimals <= PRICING_DECIMALS) { diffDecimals = PRICING_DECIMALS.sub(ivDecimals); } else { diffDecimals = ivDecimals.sub(PRICING_DECIMALS); } return oracleIV.div(10**diffDecimals); } function _getAdjustedIV(address optionAddress, uint256 currentIV) internal view returns (uint256 adjustedIV) { uint256 oracleIV = _getOracleIV(optionAddress); adjustedIV = _ORACLE_IV_WEIGHT.mul(oracleIV).add(_POOL_IV_WEIGHT.mul(currentIV)).div( _POOL_IV_WEIGHT + _ORACLE_IV_WEIGHT ); } function _getNewIV( uint256 newTargetABPrice, uint256 spotPrice, uint256 timeToMaturity ) internal view returns (uint256) { uint256 newTargetABPriceWithDecimals = newTargetABPrice.mul(10**(PRICING_DECIMALS.sub(tokenBDecimals()))); uint256 newIV; IIVGuesser ivGuesser = IIVGuesser(configurationManager.getIVGuesser()); if (priceProperties.optionType == IPodOption.OptionType.PUT) { (newIV, ) = ivGuesser.getPutIV( newTargetABPriceWithDecimals, priceProperties.initialIVGuess, spotPrice, priceProperties.strikePrice, timeToMaturity, priceProperties.riskFree ); } else { (newIV, ) = ivGuesser.getCallIV( newTargetABPriceWithDecimals, priceProperties.initialIVGuess, spotPrice, priceProperties.strikePrice, timeToMaturity, priceProperties.riskFree ); } return newIV; } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountBOutPool The exact amount of tokenB will leave the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountAInPool The amount of tokenA(options) will enter the pool */ function _getAmountAInPool( uint256 amountBOutPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountAInPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); require(amountBOutPool < poolAmountB, "AMM: insufficient liquidity"); amountAInPool = productConstant.div(poolAmountB.sub(amountBOutPool)).sub(poolAmountA); } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountBInPool The exact amount of tokenB will enter the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountAOutPool The amount of tokenA(options) will leave the pool */ function _getAmountAOutPool( uint256 amountBInPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountAOutPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); amountAOutPool = poolAmountA.sub(productConstant.div(poolAmountB.add(amountBInPool))); } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountAOutPool The amount of tokenA(options) will leave the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountBInPool The amount of tokenB will enter the pool */ function _getAmountBInPool( uint256 amountAOutPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountBInPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); require(amountAOutPool < poolAmountA, "AMM: insufficient liquidity"); amountBInPool = productConstant.div(poolAmountA.sub(amountAOutPool)).sub(poolAmountB); } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountAInPool The exact amount of tokenA(options) will enter the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountBOutPool The amount of tokenB will leave the pool */ function _getAmountBOutPool( uint256 amountAInPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountBOutPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); amountBOutPool = poolAmountB.sub(productConstant.div(poolAmountA.add(amountAInPool))); } /** * @dev Based on the tokensA and tokensB leaving or entering the pool, it is possible to calculate the new option * target price. That price will be used later to update the currentIV. * @param newABPrice calculated Black Scholes unit price (how many units of tokenB, to buy 1 tokenA(option)) * @param amountA The amount of tokenA that will leave or enter the pool * @param amountB TThe amount of tokenB that will leave or enter the pool * @param tradeDirection The trade direction, if it is AB, means that tokenA will enter, and tokenB will leave. * @return newTargetPrice The new unit target price (how many units of tokenB, to buy 1 tokenA(option)) */ function _getNewTargetPrice( uint256 newABPrice, uint256 amountA, uint256 amountB, TradeDirection tradeDirection ) internal view returns (uint256 newTargetPrice) { (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); if (tradeDirection == TradeDirection.AB) { newTargetPrice = poolAmountB.sub(amountB).mul(10**uint256(tokenADecimals())).div(poolAmountA.add(amountA)); } else { newTargetPrice = poolAmountB.add(amountB).mul(10**uint256(tokenADecimals())).div(poolAmountA.sub(amountA)); } } function _getTradeDetailsExactAInput(uint256 exactAmountAIn) internal override returns (TradeDetails memory) { (uint256 amountBOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactAInput( exactAmountAIn ); TradeDetails memory tradeDetails = TradeDetails(amountBOut, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } function _getTradeDetailsExactAOutput(uint256 exactAmountAOut) internal override returns (TradeDetails memory) { (uint256 amountBIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactAOutput( exactAmountAOut ); TradeDetails memory tradeDetails = TradeDetails(amountBIn, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } function _getTradeDetailsExactBInput(uint256 exactAmountBIn) internal override returns (TradeDetails memory) { (uint256 amountAOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactBInput( exactAmountBIn ); TradeDetails memory tradeDetails = TradeDetails(amountAOut, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } function _getTradeDetailsExactBOutput(uint256 exactAmountBOut) internal override returns (TradeDetails memory) { (uint256 amountAIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactBOutput( exactAmountBOut ); TradeDetails memory tradeDetails = TradeDetails(amountAIn, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } /** * @dev If a option is ITM, either PUTs or CALLs, the minimum price that it would cost is the difference between * the spot price and strike price. If the target price after applying slippage is above this minimum, the function * returns true. * @param newTargetPrice the new ABPrice after slippage (how many units of tokenB, to buy 1 option) * @param spotPrice current underlying asset spot price during this transaction * @return true if is a valid target price (above the minimum) */ function _isValidTargetPrice(uint256 newTargetPrice, uint256 spotPrice) internal view returns (bool) { if (priceProperties.optionType == IPodOption.OptionType.PUT) { if (spotPrice < priceProperties.strikePrice) { return newTargetPrice > priceProperties.strikePrice.sub(spotPrice).div(10**PRICING_DECIMALS.sub(tokenBDecimals())); } } else { if (spotPrice > priceProperties.strikePrice) { return newTargetPrice > spotPrice.sub(priceProperties.strikePrice).div(10**PRICING_DECIMALS.sub(tokenBDecimals())); } } return true; } function _onAddLiquidity(UserDepositSnapshot memory _userDepositSnapshot, address owner) internal override { uint256 currentQuotesA = feePoolA.sharesOf(owner); uint256 currentQuotesB = feePoolB.sharesOf(owner); uint256 amountOfQuotesAToAdd = 0; uint256 amountOfQuotesBToAdd = 0; uint256 totalQuotesA = _userDepositSnapshot.tokenABalance.mul(10**FIMP_DECIMALS).div(_userDepositSnapshot.fImp); if (totalQuotesA > currentQuotesA) { amountOfQuotesAToAdd = totalQuotesA.sub(currentQuotesA); } uint256 totalQuotesB = _userDepositSnapshot.tokenBBalance.mul(10**FIMP_DECIMALS).div(_userDepositSnapshot.fImp); if (totalQuotesB > currentQuotesB) { amountOfQuotesBToAdd = totalQuotesB.sub(currentQuotesB); } feePoolA.mint(owner, amountOfQuotesAToAdd); feePoolB.mint(owner, amountOfQuotesBToAdd); } function _onRemoveLiquidity( uint256 percentA, uint256 percentB, address owner ) internal override { (uint256 amountOfSharesAToRemove, uint256 amountOfSharesBToRemove) = _getAmountOfFeeShares( percentA, percentB, owner ); if (amountOfSharesAToRemove > 0) { feePoolA.withdraw(owner, amountOfSharesAToRemove); } if (amountOfSharesBToRemove > 0) { feePoolB.withdraw(owner, amountOfSharesBToRemove); } } function _getAmountOfFeeShares( uint256 percentA, uint256 percentB, address owner ) internal view returns (uint256, uint256) { uint256 currentSharesA = feePoolA.sharesOf(owner); uint256 currentSharesB = feePoolB.sharesOf(owner); uint256 amountOfSharesAToRemove = currentSharesA.mul(percentA).div(PERCENT_PRECISION); uint256 amountOfSharesBToRemove = currentSharesB.mul(percentB).div(PERCENT_PRECISION); return (amountOfSharesAToRemove, amountOfSharesBToRemove); } function _onTrade(TradeDetails memory tradeDetails) internal override { uint256 newIV = abi.decode(tradeDetails.params, (uint256)); priceProperties.currentIV = newIV; IERC20(tokenB()).safeTransfer(address(feePoolA), tradeDetails.feesTokenA); IERC20(tokenB()).safeTransfer(address(feePoolB), tradeDetails.feesTokenB); } /** * @dev Check for functions which are only allowed to be executed * BEFORE start of exercise window. */ function _beforeStartOfExerciseWindow() internal view { require(block.timestamp < priceProperties.startOfExerciseWindow, "Pool: exercise window has started"); } function _emergencyStopCheck() private view { IEmergencyStop emergencyStop = IEmergencyStop(configurationManager.getEmergencyStop()); require( !emergencyStop.isStopped(address(this)) && !emergencyStop.isStopped(configurationManager.getPriceProvider()) && !emergencyStop.isStopped(configurationManager.getPricingMethod()), "Pool: Pool is stopped" ); } function _emitTradeInfo() private { uint256 spotPrice = _getSpotPrice(priceProperties.underlyingAsset, PRICING_DECIMALS); emit TradeInfo(spotPrice, priceProperties.currentIV); } } // 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.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 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: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../lib/RequiredDecimals.sol"; import "../interfaces/IAMM.sol"; /** * Represents a generalized contract for a single-sided AMM pair. * * That means is possible to add and remove liquidity in any proportion * at any time, even 0 in one of the sides. * * The AMM is constituted by 3 core functions: Add Liquidity, Remove liquidity and Trade. * * There are 4 possible trade types between the token pair (tokenA and tokenB): * * - ExactAInput: * tokenA as an exact Input, meaning that the output tokenB is variable. * it is important to have a slippage control of the minimum acceptable amount of tokenB in return * - ExactAOutput: * tokenA as an exact Output, meaning that the input tokenB is variable. * it is important to have a slippage control of the maximum acceptable amount of tokenB sent * - ExactBInput: * tokenB as an exact Input, meaning that the output tokenA is variable. * it is important to have a slippage control of the minimum acceptable amount of tokenA in return * - ExactBOutput: * tokenB as an exact Output, meaning that the input tokenA is variable. * it is important to have a slippage control of the maximum acceptable amount of tokenA sent * * Several functions are provided as virtual and must be overridden by the inheritor. * * - _getABPrice: * function that will return the tokenA:tokenB price relation. * How many units of tokenB in order to traded for 1 unit of tokenA. * This price is represented in the same tokenB number of decimals. * - _onAddLiquidity: * Executed after adding liquidity. Usually used for handling fees * - _onRemoveLiquidity: * Executed after removing liquidity. Usually used for handling fees * * Also, for which TradeType (E.g: ExactAInput) there are more two functions to override: * _getTradeDetails[$TradeType]: * This function is responsible to return the TradeDetails struct, that contains basically the amount * of the other token depending on the trade type. (E.g: ExactAInput => The TradeDetails will return the * amount of B output). * _onTrade[$TradeType]: * function that will be executed after UserDepositSnapshot updates and before * token transfers. Usually used for handling fees and updating state at the inheritor. * */ abstract contract AMM is IAMM, RequiredDecimals { using SafeERC20 for IERC20; using SafeMath for uint256; /** * @dev The initial value for deposit factor (Fimp) */ uint256 public constant INITIAL_FIMP = 10**27; /** * @notice The Fimp's precision (aka number of decimals) */ uint256 public constant FIMP_DECIMALS = 27; /** * @notice The percent's precision */ uint256 public constant PERCENT_PRECISION = 100; /** * @dev Address of the token A */ address private _tokenA; /** * @dev Address of the token B */ address private _tokenB; /** * @dev Token A number of decimals */ uint8 private _tokenADecimals; /** * @dev Token B number of decimals */ uint8 private _tokenBDecimals; /** * @notice The total balance of token A in the pool not counting the amortization */ uint256 public deamortizedTokenABalance; /** * @notice The total balance of token B in the pool not counting the amortization */ uint256 public deamortizedTokenBBalance; /** * @notice It contains the token A original balance, token B original balance, * and the Open Value Factor (Fimp) at the time of the deposit. */ struct UserDepositSnapshot { uint256 tokenABalance; uint256 tokenBBalance; uint256 fImp; } struct Mult { uint256 AA; // How much A Im getting for rescuing one A that i've deposited uint256 AB; // How much B Im getting for rescuing one A that i've deposited uint256 BA; // How much A Im getting for rescuing one B that i've deposited uint256 BB; // How much B Im getting for rescuing one B that i've deposited } struct TradeDetails { uint256 amount; uint256 feesTokenA; uint256 feesTokenB; bytes params; } /** * @dev Tracks the UserDepositSnapshot struct of each user. * It contains the token A original balance, token B original balance, * and the Open Value Factor (Fimp) at the time of the deposit. */ mapping(address => UserDepositSnapshot) private _userSnapshots; /** Events */ event AddLiquidity(address indexed caller, address indexed owner, uint256 amountA, uint256 amountB); event RemoveLiquidity(address indexed caller, uint256 amountA, uint256 amountB); event TradeExactAInput(address indexed caller, address indexed owner, uint256 exactAmountAIn, uint256 amountBOut); event TradeExactBInput(address indexed caller, address indexed owner, uint256 exactAmountBIn, uint256 amountAOut); event TradeExactAOutput(address indexed caller, address indexed owner, uint256 amountBIn, uint256 exactAmountAOut); event TradeExactBOutput(address indexed caller, address indexed owner, uint256 amountAIn, uint256 exactAmountBOut); constructor(address tokenA, address tokenB) public { require(Address.isContract(tokenA), "AMM: token a is not a contract"); require(Address.isContract(tokenB), "AMM: token b is not a contract"); require(tokenA != tokenB, "AMM: tokens must differ"); _tokenA = tokenA; _tokenB = tokenB; _tokenADecimals = tryDecimals(IERC20(tokenA)); _tokenBDecimals = tryDecimals(IERC20(tokenB)); } /** * @dev Returns the address for tokenA */ function tokenA() public override view returns (address) { return _tokenA; } /** * @dev Returns the address for tokenB */ function tokenB() public override view returns (address) { return _tokenB; } /** * @dev Returns the decimals for tokenA */ function tokenADecimals() public override view returns (uint8) { return _tokenADecimals; } /** * @dev Returns the decimals for tokenB */ function tokenBDecimals() public override view returns (uint8) { return _tokenBDecimals; } /** * @notice getPoolBalances external function that returns the current pool balance of token A and token B * * @return totalTokenA balanceOf this contract of token A * @return totalTokenB balanceOf this contract of token B */ function getPoolBalances() external view returns (uint256 totalTokenA, uint256 totalTokenB) { return _getPoolBalances(); } /** * @notice getUserDepositSnapshot external function that User original balance of token A, * token B and the Opening Value * * Factor (Fimp) at the moment of the liquidity added * * @param user address to check the balance info * * @return tokenAOriginalBalance balance of token A by the moment of deposit * @return tokenBOriginalBalance balance of token B by the moment of deposit * @return fImpUser value of the Opening Value Factor by the moment of the deposit */ function getUserDepositSnapshot(address user) external view returns ( uint256 tokenAOriginalBalance, uint256 tokenBOriginalBalance, uint256 fImpUser ) { return _getUserDepositSnapshot(user); } /** * @notice _addLiquidity in any proportion of tokenA or tokenB * * @dev The inheritor contract should implement _getABPrice and _onAddLiquidity functions * * @param amountOfA amount of TokenA to add * @param amountOfB amount of TokenB to add * @param owner address of the account that will have ownership of the liquidity */ function _addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner ) internal { _isValidAddress(owner); // Get Pool Balances (uint256 totalTokenA, uint256 totalTokenB) = _getPoolBalances(); bool hasNoLiquidity = deamortizedTokenABalance == 0 && deamortizedTokenBBalance == 0; uint256 fImpOpening; uint256 userAmountToStoreTokenA = amountOfA; uint256 userAmountToStoreTokenB = amountOfB; if (hasNoLiquidity) { // In the first liquidity, is necessary add both tokens bool bothTokensHigherThanZero = amountOfA > 0 && amountOfB > 0; require(bothTokensHigherThanZero, "AMM: invalid first liquidity"); fImpOpening = INITIAL_FIMP; deamortizedTokenABalance = amountOfA; deamortizedTokenBBalance = amountOfB; } else { // Get ABPrice uint256 ABPrice = _getABPrice(); require(ABPrice > 0, "AMM: option price zero"); // Calculate the Pool's Value Factor (Fimp) fImpOpening = _getFImpOpening( totalTokenA, totalTokenB, ABPrice, deamortizedTokenABalance, deamortizedTokenBBalance ); (userAmountToStoreTokenA, userAmountToStoreTokenB) = _getUserBalanceToStore( amountOfA, amountOfB, fImpOpening, _userSnapshots[owner] ); // Update Deamortized Balance of the pool for each token; deamortizedTokenABalance = deamortizedTokenABalance.add(amountOfA.mul(10**FIMP_DECIMALS).div(fImpOpening)); deamortizedTokenBBalance = deamortizedTokenBBalance.add(amountOfB.mul(10**FIMP_DECIMALS).div(fImpOpening)); } // Update the User Balances for each token and with the Pool Factor previously calculated UserDepositSnapshot memory userDepositSnapshot = UserDepositSnapshot( userAmountToStoreTokenA, userAmountToStoreTokenB, fImpOpening ); _userSnapshots[owner] = userDepositSnapshot; _onAddLiquidity(_userSnapshots[owner], owner); // Update Total Balance of the pool for each token if (amountOfA > 0) { IERC20(_tokenA).safeTransferFrom(msg.sender, address(this), amountOfA); } if (amountOfB > 0) { IERC20(_tokenB).safeTransferFrom(msg.sender, address(this), amountOfB); } emit AddLiquidity(msg.sender, owner, amountOfA, amountOfB); } /** * @notice _removeLiquidity in any proportion of tokenA or tokenB * @dev The inheritor contract should implement _getABPrice and _onRemoveLiquidity functions * * @param percentA proportion of the exposition of the original tokenA that want to be removed * @param percentB proportion of the exposition of the original tokenB that want to be removed */ function _removeLiquidity(uint256 percentA, uint256 percentB) internal { (uint256 userTokenABalance, uint256 userTokenBBalance, uint256 userFImp) = _getUserDepositSnapshot(msg.sender); require(percentA <= 100 && percentB <= 100, "AMM: forbidden percent"); uint256 originalBalanceAToReduce = percentA.mul(userTokenABalance).div(PERCENT_PRECISION); uint256 originalBalanceBToReduce = percentB.mul(userTokenBBalance).div(PERCENT_PRECISION); // Get Pool Balances (uint256 totalTokenA, uint256 totalTokenB) = _getPoolBalances(); // Get ABPrice uint256 ABPrice = _getABPrice(); // Calculate the Pool's Value Factor (Fimp) uint256 fImpOpening = _getFImpOpening( totalTokenA, totalTokenB, ABPrice, deamortizedTokenABalance, deamortizedTokenBBalance ); // Calculate Multipliers Mult memory multipliers = _getMultipliers(totalTokenA, totalTokenB, fImpOpening); // Update User balance _userSnapshots[msg.sender].tokenABalance = userTokenABalance.sub(originalBalanceAToReduce); _userSnapshots[msg.sender].tokenBBalance = userTokenBBalance.sub(originalBalanceBToReduce); // Update deamortized balance deamortizedTokenABalance = deamortizedTokenABalance.sub( originalBalanceAToReduce.mul(10**FIMP_DECIMALS).div(userFImp) ); deamortizedTokenBBalance = deamortizedTokenBBalance.sub( originalBalanceBToReduce.mul(10**FIMP_DECIMALS).div(userFImp) ); // Calculate amount to send (uint256 withdrawAmountA, uint256 withdrawAmountB) = _getWithdrawAmounts( originalBalanceAToReduce, originalBalanceBToReduce, userFImp, multipliers ); if (withdrawAmountA > totalTokenA) { withdrawAmountA = totalTokenA; } if (withdrawAmountB > totalTokenB) { withdrawAmountB = totalTokenB; } _onRemoveLiquidity(percentA, percentB, msg.sender); // Transfers / Update if (withdrawAmountA > 0) { IERC20(_tokenA).safeTransfer(msg.sender, withdrawAmountA); } if (withdrawAmountB > 0) { IERC20(_tokenB).safeTransfer(msg.sender, withdrawAmountB); } emit RemoveLiquidity(msg.sender, withdrawAmountA, withdrawAmountB); } /** * @notice _tradeExactAInput msg.sender is able to trade exact amount of token A in exchange for minimum * amount of token B sent by the contract to the owner * @dev The inheritor contract should implement _getTradeDetailsExactAInput and _onTradeExactAInput functions * _getTradeDetailsExactAInput should return tradeDetails struct format * * @param exactAmountAIn exact amount of A token that will be transfer from msg.sender * @param minAmountBOut minimum acceptable amount of token B to transfer to owner * @param owner the destination address that will receive the token B */ function _tradeExactAInput( uint256 exactAmountAIn, uint256 minAmountBOut, address owner ) internal returns (uint256) { _isValidInput(exactAmountAIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactAInput(exactAmountAIn); uint256 amountBOut = tradeDetails.amount; require(amountBOut > 0, "AMM: invalid amountBOut"); require(amountBOut >= minAmountBOut, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenA).safeTransferFrom(msg.sender, address(this), exactAmountAIn); IERC20(_tokenB).safeTransfer(owner, amountBOut); emit TradeExactAInput(msg.sender, owner, exactAmountAIn, amountBOut); return amountBOut; } /** * @notice _tradeExactAOutput owner is able to receive exact amount of token A in exchange of a max * acceptable amount of token B sent by the msg.sender to the contract * * @dev The inheritor contract should implement _getTradeDetailsExactAOutput and _onTradeExactAOutput functions * _getTradeDetailsExactAOutput should return tradeDetails struct format * * @param exactAmountAOut exact amount of token A that will be transfer to owner * @param maxAmountBIn maximum acceptable amount of token B to transfer from msg.sender * @param owner the destination address that will receive the token A */ function _tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner ) internal returns (uint256) { _isValidInput(maxAmountBIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactAOutput(exactAmountAOut); uint256 amountBIn = tradeDetails.amount; require(amountBIn > 0, "AMM: invalid amountBIn"); require(amountBIn <= maxAmountBIn, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenB).safeTransferFrom(msg.sender, address(this), amountBIn); IERC20(_tokenA).safeTransfer(owner, exactAmountAOut); emit TradeExactAOutput(msg.sender, owner, amountBIn, exactAmountAOut); return amountBIn; } /** * @notice _tradeExactBInput msg.sender is able to trade exact amount of token B in exchange for minimum * amount of token A sent by the contract to the owner * * @dev The inheritor contract should implement _getTradeDetailsExactBInput and _onTradeExactBInput functions * _getTradeDetailsExactBInput should return tradeDetails struct format * * @param exactAmountBIn exact amount of token B that will be transfer from msg.sender * @param minAmountAOut minimum acceptable amount of token A to transfer to owner * @param owner the destination address that will receive the token A */ function _tradeExactBInput( uint256 exactAmountBIn, uint256 minAmountAOut, address owner ) internal returns (uint256) { _isValidInput(exactAmountBIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactBInput(exactAmountBIn); uint256 amountAOut = tradeDetails.amount; require(amountAOut > 0, "AMM: invalid amountAOut"); require(amountAOut >= minAmountAOut, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenB).safeTransferFrom(msg.sender, address(this), exactAmountBIn); IERC20(_tokenA).safeTransfer(owner, amountAOut); emit TradeExactBInput(msg.sender, owner, exactAmountBIn, amountAOut); return amountAOut; } /** * @notice _tradeExactBOutput owner is able to receive exact amount of token B from the contract in exchange of a * max acceptable amount of token A sent by the msg.sender to the contract. * * @dev The inheritor contract should implement _getTradeDetailsExactBOutput and _onTradeExactBOutput functions * _getTradeDetailsExactBOutput should return tradeDetails struct format * * @param exactAmountBOut exact amount of token B that will be transfer to owner * @param maxAmountAIn maximum acceptable amount of token A to transfer from msg.sender * @param owner the destination address that will receive the token B */ function _tradeExactBOutput( uint256 exactAmountBOut, uint256 maxAmountAIn, address owner ) internal returns (uint256) { _isValidInput(maxAmountAIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactBOutput(exactAmountBOut); uint256 amountAIn = tradeDetails.amount; require(amountAIn > 0, "AMM: invalid amountAIn"); require(amountAIn <= maxAmountAIn, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenA).safeTransferFrom(msg.sender, address(this), amountAIn); IERC20(_tokenB).safeTransfer(owner, exactAmountBOut); emit TradeExactBOutput(msg.sender, owner, amountAIn, exactAmountBOut); return amountAIn; } /** * @notice _getFImpOpening Auxiliary function that calculate the Opening Value Factor Fimp * * @param _totalTokenA total contract balance of token A * @param _totalTokenB total contract balance of token B * @param _ABPrice Unit price AB, meaning, how many units of token B could buy 1 unit of token A * @param _deamortizedTokenABalance contract deamortized balance of token A * @param _deamortizedTokenBBalance contract deamortized balance of token B * @return fImpOpening Opening Value Factor Fimp */ function _getFImpOpening( uint256 _totalTokenA, uint256 _totalTokenB, uint256 _ABPrice, uint256 _deamortizedTokenABalance, uint256 _deamortizedTokenBBalance ) internal view returns (uint256) { uint256 numerator; uint256 denominator; { numerator = _totalTokenA.mul(_ABPrice).div(10**uint256(_tokenADecimals)).add(_totalTokenB).mul( 10**FIMP_DECIMALS ); } { denominator = _deamortizedTokenABalance.mul(_ABPrice).div(10**uint256(_tokenADecimals)).add( _deamortizedTokenBBalance ); } return numerator.div(denominator); } /** * @notice _getPoolBalances external function that returns the current pool balance of token A and token B * * @return totalTokenA balanceOf this contract of token A * @return totalTokenB balanceOf this contract of token B */ function _getPoolBalances() internal view returns (uint256 totalTokenA, uint256 totalTokenB) { totalTokenA = IERC20(_tokenA).balanceOf(address(this)); totalTokenB = IERC20(_tokenB).balanceOf(address(this)); } /** * @notice _getUserDepositSnapshot internal function that User original balance of token A, * token B and the Opening Value * * Factor (Fimp) at the moment of the liquidity added * * @param user address of the user that want to check the balance * * @return tokenAOriginalBalance balance of token A by the moment of deposit * @return tokenBOriginalBalance balance of token B by the moment of deposit * @return fImpOriginal value of the Opening Value Factor by the moment of the deposit */ function _getUserDepositSnapshot(address user) internal view returns ( uint256 tokenAOriginalBalance, uint256 tokenBOriginalBalance, uint256 fImpOriginal ) { tokenAOriginalBalance = _userSnapshots[user].tokenABalance; tokenBOriginalBalance = _userSnapshots[user].tokenBBalance; fImpOriginal = _userSnapshots[user].fImp; } /** * @notice _getMultipliers internal function that calculate new multipliers based on the current pool position * * mAA => How much A the users can rescue for each A they deposited * mBA => How much A the users can rescue for each B they deposited * mBB => How much B the users can rescue for each B they deposited * mAB => How much B the users can rescue for each A they deposited * * @param totalTokenA balanceOf this contract of token A * @param totalTokenB balanceOf this contract of token B * @param fImpOpening current Open Value Factor * @return multipliers multiplier struct containing the 4 multipliers: mAA, mBA, mBB, mAB */ function _getMultipliers( uint256 totalTokenA, uint256 totalTokenB, uint256 fImpOpening ) internal view returns (Mult memory multipliers) { uint256 totalTokenAWithPrecision = totalTokenA.mul(10**FIMP_DECIMALS); uint256 totalTokenBWithPrecision = totalTokenB.mul(10**FIMP_DECIMALS); uint256 mAA = 0; uint256 mBB = 0; uint256 mAB = 0; uint256 mBA = 0; if (deamortizedTokenABalance > 0) { mAA = (_min(deamortizedTokenABalance.mul(fImpOpening), totalTokenAWithPrecision)).div( deamortizedTokenABalance ); } if (deamortizedTokenBBalance > 0) { mBB = (_min(deamortizedTokenBBalance.mul(fImpOpening), totalTokenBWithPrecision)).div( deamortizedTokenBBalance ); } if (mAA > 0) { mAB = totalTokenBWithPrecision.sub(mBB.mul(deamortizedTokenBBalance)).div(deamortizedTokenABalance); } if (mBB > 0) { mBA = totalTokenAWithPrecision.sub(mAA.mul(deamortizedTokenABalance)).div(deamortizedTokenBBalance); } multipliers = Mult(mAA, mAB, mBA, mBB); } /** * @notice _getRemoveLiquidityAmounts internal function of getRemoveLiquidityAmounts * * @param percentA percent of exposition A to be removed * @param percentB percent of exposition B to be removed * @param user address of the account that will be removed * * @return withdrawAmountA amount of token A that will be rescued * @return withdrawAmountB amount of token B that will be rescued */ function _getRemoveLiquidityAmounts( uint256 percentA, uint256 percentB, address user ) internal view returns (uint256 withdrawAmountA, uint256 withdrawAmountB) { (uint256 totalTokenA, uint256 totalTokenB) = _getPoolBalances(); (uint256 originalBalanceTokenA, uint256 originalBalanceTokenB, uint256 fImpOriginal) = _getUserDepositSnapshot( user ); uint256 originalBalanceAToReduce = percentA.mul(originalBalanceTokenA).div(PERCENT_PRECISION); uint256 originalBalanceBToReduce = percentB.mul(originalBalanceTokenB).div(PERCENT_PRECISION); bool hasNoLiquidity = totalTokenA == 0 && totalTokenB == 0; if (hasNoLiquidity) { return (0, 0); } uint256 ABPrice = _getABPrice(); uint256 fImpOpening = _getFImpOpening( totalTokenA, totalTokenB, ABPrice, deamortizedTokenABalance, deamortizedTokenBBalance ); Mult memory multipliers = _getMultipliers(totalTokenA, totalTokenB, fImpOpening); (withdrawAmountA, withdrawAmountB) = _getWithdrawAmounts( originalBalanceAToReduce, originalBalanceBToReduce, fImpOriginal, multipliers ); } /** * @notice _getWithdrawAmounts internal function of getRemoveLiquidityAmounts * * @param _originalBalanceAToReduce amount of original deposit of the token A * @param _originalBalanceBToReduce amount of original deposit of the token B * @param _userFImp Opening Value Factor by the moment of the deposit * * @return withdrawAmountA amount of token A that will be rescued * @return withdrawAmountB amount of token B that will be rescued */ function _getWithdrawAmounts( uint256 _originalBalanceAToReduce, uint256 _originalBalanceBToReduce, uint256 _userFImp, Mult memory multipliers ) internal pure returns (uint256 withdrawAmountA, uint256 withdrawAmountB) { if (_userFImp > 0) { withdrawAmountA = _originalBalanceAToReduce .mul(multipliers.AA) .add(_originalBalanceBToReduce.mul(multipliers.BA)) .div(_userFImp); withdrawAmountB = _originalBalanceBToReduce .mul(multipliers.BB) .add(_originalBalanceAToReduce.mul(multipliers.AB)) .div(_userFImp); } return (withdrawAmountA, withdrawAmountB); } /** * @notice _getUserBalanceToStore internal auxiliary function to help calculation the * tokenA and tokenB value that should be stored in UserDepositSnapshot struct * * @param amountOfA current deposit of the token A * @param amountOfB current deposit of the token B * @param fImpOpening Opening Value Factor by the moment of the deposit * * @return userToStoreTokenA amount of token A that will be stored * @return userToStoreTokenB amount of token B that will be stored */ function _getUserBalanceToStore( uint256 amountOfA, uint256 amountOfB, uint256 fImpOpening, UserDepositSnapshot memory userDepositSnapshot ) internal pure returns (uint256 userToStoreTokenA, uint256 userToStoreTokenB) { userToStoreTokenA = amountOfA; userToStoreTokenB = amountOfB; //Re-add Liquidity case if (userDepositSnapshot.fImp != 0) { userToStoreTokenA = userDepositSnapshot.tokenABalance.mul(fImpOpening).div(userDepositSnapshot.fImp).add( amountOfA ); userToStoreTokenB = userDepositSnapshot.tokenBBalance.mul(fImpOpening).div(userDepositSnapshot.fImp).add( amountOfB ); } } /** * @dev Returns the smallest of two numbers. */ function _min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function _getABPrice() internal virtual view returns (uint256 ABPrice); function _getTradeDetailsExactAInput(uint256 amountAIn) internal virtual returns (TradeDetails memory); function _getTradeDetailsExactAOutput(uint256 amountAOut) internal virtual returns (TradeDetails memory); function _getTradeDetailsExactBInput(uint256 amountBIn) internal virtual returns (TradeDetails memory); function _getTradeDetailsExactBOutput(uint256 amountBOut) internal virtual returns (TradeDetails memory); function _onTrade(TradeDetails memory tradeDetails) internal virtual; function _onRemoveLiquidity( uint256 percentA, uint256 percentB, address owner ) internal virtual; function _onAddLiquidity(UserDepositSnapshot memory userDepositSnapshot, address owner) internal virtual; function _isValidAddress(address recipient) private pure { require(recipient != address(0), "AMM: transfer to zero address"); } function _isValidInput(uint256 input) private pure { require(input > 0, "AMM: input should be greater than zero"); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IConfigurationManager.sol"; import "../interfaces/ICapProvider.sol"; /** * @title CappedPool * @author Pods Finance * * @notice Controls a maximum cap for a guarded release */ abstract contract CappedPool { using SafeMath for uint256; IConfigurationManager private immutable _configurationManager; constructor(IConfigurationManager configurationManager) public { _configurationManager = configurationManager; } /** * @dev Modifier to stop transactions that exceed the cap */ modifier capped(address token, uint256 amountOfLiquidity) { uint256 cap = capSize(); if (cap > 0) { uint256 poolBalance = IERC20(token).balanceOf(address(this)); require(poolBalance.add(amountOfLiquidity) <= cap, "CappedPool: amount exceed cap"); } _; } /** * @dev Get the cap size */ function capSize() public view returns (uint256) { ICapProvider capProvider = ICapProvider(_configurationManager.getCapProvider()); return capProvider.getCap(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; contract CombinedActionsGuard { mapping(address => uint256) sessions; /** * @dev Prevents an address from calling more than one function that contains this * function in the same block */ function _nonCombinedActions() internal { require(sessions[tx.origin] != block.number, "CombinedActionsGuard: reentrant call"); sessions[tx.origin] = block.number; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IPriceProvider { function setAssetFeeds(address[] memory _assets, address[] memory _feeds) external; function updateAssetFeeds(address[] memory _assets, address[] memory _feeds) external; function removeAssetFeeds(address[] memory _assets) external; function getAssetPrice(address _asset) external view returns (uint256); function getAssetDecimals(address _asset) external view returns (uint8); function latestRoundData(address _asset) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getPriceFeed(address _asset) external view returns (address); function updateMinUpdateInterval() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IIVProvider { struct IVData { uint256 roundId; uint256 updatedAt; uint256 answer; uint8 decimals; } event UpdatedIV(address indexed option, uint256 roundId, uint256 updatedAt, uint256 answer, uint8 decimals); event UpdaterSet(address indexed admin, address indexed updater); function getIV(address option) external view returns ( uint256 roundId, uint256 updatedAt, uint256 answer, uint8 decimals ); function updateIV( address option, uint256 answer, uint8 decimals ) external; function setUpdater(address updater) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity >=0.6.12; interface IBlackScholes { function getCallPrice( uint256 spotPrice, uint256 strikePrice, uint256 sigma, uint256 time, int256 riskFree ) external view returns (uint256); function getPutPrice( uint256 spotPrice, uint256 strikePrice, uint256 sigma, uint256 time, int256 riskFree ) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IIVGuesser { function blackScholes() external view returns (address); function getPutIV( uint256 _targetPrice, uint256 _initialIVGuess, uint256 _spotPrice, uint256 _strikePrice, uint256 _timeToMaturity, int256 _riskFree ) external view returns (uint256, uint256); function getCallIV( uint256 _targetPrice, uint256 _initialIVGuess, uint256 _spotPrice, uint256 _strikePrice, uint256 _timeToMaturity, int256 _riskFree ) external view returns (uint256, uint256); function updateAcceptableRange() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPodOption is IERC20 { /** Enums */ // @dev 0 for Put, 1 for Call enum OptionType { PUT, CALL } // @dev 0 for European, 1 for American enum ExerciseType { EUROPEAN, AMERICAN } /** Events */ event Mint(address indexed minter, uint256 amount); event Unmint(address indexed minter, uint256 optionAmount, uint256 strikeAmount, uint256 underlyingAmount); event Exercise(address indexed exerciser, uint256 amount); event Withdraw(address indexed minter, uint256 strikeAmount, uint256 underlyingAmount); /** Functions */ /** * @notice Locks collateral and write option tokens. * * @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token. * * The collateral could be the strike or the underlying asset depending on the option type: Put or Call, * respectively * * It presumes the caller has already called IERC20.approve() on the * strike/underlying token contract to move caller funds. * * Options can only be minted while the series is NOT expired. * * It is also important to notice that options will be sent back * to `msg.sender` and not the `owner`. This behavior is designed to allow * proxy contracts to mint on others behalf. The `owner` will be able to remove * the deposited collateral after series expiration or by calling unmint(), even * if a third-party minted options on its behalf. * * @param amountOfOptions The amount option tokens to be issued * @param owner Which address will be the owner of the options */ function mint(uint256 amountOfOptions, address owner) external; /** * @notice Allow option token holders to use them to exercise the amount of units * of the locked tokens for the equivalent amount of the exercisable assets. * * @dev It presumes the caller has already called IERC20.approve() exercisable asset * to move caller funds. * * On American options, this function can only called anytime before expiration. * For European options, this function can only be called during the exerciseWindow. * Meaning, after expiration and before the end of exercise window. * * @param amountOfOptions The amount option tokens to be exercised */ function exercise(uint256 amountOfOptions) external; /** * @notice After series expiration in case of American or after exercise window for European, * allow minters who have locked their collateral to withdraw them proportionally * to their minted options. * * @dev If assets had been exercised during the option series the minter may withdraw * the exercised assets or a combination of exercised and collateral. */ function withdraw() external; /** * @notice Unlocks collateral by burning option tokens. * * Options can only be burned while the series is NOT expired. * * @param amountOfOptions The amount option tokens to be burned */ function unmint(uint256 amountOfOptions) external; function optionType() external view returns (OptionType); function exerciseType() external view returns (ExerciseType); function underlyingAsset() external view returns (address); function underlyingAssetDecimals() external view returns (uint8); function strikeAsset() external view returns (address); function strikeAssetDecimals() external view returns (uint8); function strikePrice() external view returns (uint256); function strikePriceDecimals() external view returns (uint8); function expiration() external view returns (uint256); function startOfExerciseWindow() external view returns (uint256); function hasExpired() external view returns (bool); function isTradeWindow() external view returns (bool); function isExerciseWindow() external view returns (bool); function isWithdrawWindow() external view returns (bool); function strikeToTransfer(uint256 amountOfOptions) external view returns (uint256); function getSellerWithdrawAmounts(address owner) external view returns (uint256 strikeAmount, uint256 underlyingAmount); function underlyingReserves() external view returns (uint256); function strikeReserves() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "./IAMM.sol"; interface IOptionAMMPool is IAMM { // @dev 0 for when tokenA enter the pool and B leaving (A -> B) // and 1 for the opposite direction enum TradeDirection { AB, BA } function tradeExactAInput( uint256 exactAmountAIn, uint256 minAmountBOut, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function tradeExactBInput( uint256 exactAmountBIn, uint256 minAmountAOut, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function tradeExactBOutput( uint256 exactAmountBOut, uint256 maxAmountAIn, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function getOptionTradeDetailsExactAInput(uint256 exactAmountAIn) external view returns ( uint256 amountBOutput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getOptionTradeDetailsExactAOutput(uint256 exactAmountAOut) external view returns ( uint256 amountBInput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getOptionTradeDetailsExactBInput(uint256 exactAmountBIn) external view returns ( uint256 amountAOutput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getOptionTradeDetailsExactBOutput(uint256 exactAmountBOut) external view returns ( uint256 amountAInput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getRemoveLiquidityAmounts( uint256 percentA, uint256 percentB, address user ) external view returns (uint256 withdrawAmountA, uint256 withdrawAmountB); function getABPrice() external view returns (uint256); function getAdjustedIV() external view returns (uint256); function withdrawRewards() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IFeePool { struct Balance { uint256 shares; uint256 liability; } function setFee(uint256 feeBaseValue, uint8 decimals) external; function withdraw(address to, uint256 amount) external; function mint(address to, uint256 amount) external; function feeToken() external view returns (address); function feeValue() external view returns (uint256); function feeDecimals() external view returns (uint8); function getCollectable(uint256 amount, uint256 poolAmount) external view returns (uint256); function sharesOf(address owner) external view returns (uint256); function getWithdrawAmount(address owner, uint256 amountOfShares) external view returns (uint256, uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity >=0.6.12; interface IConfigurationManager { function setParameter(bytes32 name, uint256 value) external; function setEmergencyStop(address emergencyStop) external; function setPricingMethod(address pricingMethod) external; function setIVGuesser(address ivGuesser) external; function setIVProvider(address ivProvider) external; function setPriceProvider(address priceProvider) external; function setCapProvider(address capProvider) external; function setAMMFactory(address ammFactory) external; function setOptionFactory(address optionFactory) external; function setOptionHelper(address optionHelper) external; function setOptionPoolRegistry(address optionPoolRegistry) external; function getParameter(bytes32 name) external view returns (uint256); function owner() external view returns (address); function getEmergencyStop() external view returns (address); function getPricingMethod() external view returns (address); function getIVGuesser() external view returns (address); function getIVProvider() external view returns (address); function getPriceProvider() external view returns (address); function getCapProvider() external view returns (address); function getAMMFactory() external view returns (address); function getOptionFactory() external view returns (address); function getOptionHelper() external view returns (address); function getOptionPoolRegistry() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IEmergencyStop { function stop(address target) external; function resume(address target) external; function isStopped(address target) external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "./IFeePool.sol"; interface IFeePoolBuilder { function buildFeePool( address asset, uint256 feeBaseValue, uint8 feeDecimals, address owner ) external returns (IFeePool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../interfaces/IAaveIncentivesController.sol"; import "../../interfaces/IConfigurationManager.sol"; import "../../lib/Conversion.sol"; abstract contract AaveIncentives is Conversion { address public immutable rewardAsset; address public immutable rewardContract; event RewardsClaimed(address indexed claimer, uint256 rewardAmount); constructor(IConfigurationManager configurationManager) public { rewardAsset = _parseAddressFromUint(configurationManager.getParameter("REWARD_ASSET")); rewardContract = _parseAddressFromUint(configurationManager.getParameter("REWARD_CONTRACT")); } /** * @notice Gets the current reward claimed */ function _rewardBalance() internal view returns (uint256) { return IERC20(rewardAsset).balanceOf(address(this)); } /** * @notice Claim pending rewards */ function _claimRewards(address[] memory assets) internal { IAaveIncentivesController distributor = IAaveIncentivesController(rewardContract); uint256 amountToClaim = distributor.getRewardsBalance(assets, address(this)); distributor.claimRewards(assets, amountToClaim, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract RequiredDecimals { uint256 private constant _MAX_TOKEN_DECIMALS = 38; /** * Tries to fetch the decimals of a token, if not existent, fails with a require statement * * @param token An instance of IERC20 * @return The decimals of a token */ function tryDecimals(IERC20 token) internal view returns (uint8) { // solhint-disable-line private-vars-leading-underscore bytes memory payload = abi.encodeWithSignature("decimals()"); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(token).staticcall(payload); require(success, "RequiredDecimals: required decimals"); uint8 decimals = abi.decode(returnData, (uint8)); require(decimals < _MAX_TOKEN_DECIMALS, "RequiredDecimals: token decimals should be lower than 38"); return decimals; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IAMM { function addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner ) external; function removeLiquidity(uint256 amountOfA, uint256 amountOfB) external; function tokenA() external view returns (address); function tokenB() external view returns (address); function tokenADecimals() external view returns (uint8); function tokenBDecimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICapProvider { function setCap(address target, uint256 value) external; function getCap(address target) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IAaveIncentivesController { function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; contract Conversion { /** * @notice Parses the address represented by an uint */ function _parseAddressFromUint(uint256 x) internal pure returns (address) { bytes memory data = new bytes(32); assembly { mstore(add(data, 32), x) } return abi.decode(data, (address)); } }
SPDX-License-Identifier: agpl-3.0
interface IFeePoolBuilder { function buildFeePool( address asset, uint256 feeBaseValue, uint8 feeDecimals, address owner ) external returns (IFeePool); }
89,044
pragma solidity ^0.4.21; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; contract IOGToken is StandardToken, Ownable, Pausable { // events event Burn(address indexed burner, uint256 amount); event AddressLocked(address indexed _owner, uint256 _expiry); // erc20 constants string public constant name = "IOGToken"; string public constant symbol = "IOG"; uint8 public constant decimals = 18; uint256 public constant TOTAL_SUPPLY = 2200000000 * (10 ** uint256(decimals)); // lock mapping (address => uint256) public addressLocks; // constructor constructor(address[] addressList, uint256[] tokenAmountList, uint256[] lockedPeriodList) public { totalSupply_ = TOTAL_SUPPLY; balances[msg.sender] = TOTAL_SUPPLY; emit Transfer(0x0, msg.sender, TOTAL_SUPPLY); // distribution distribution(addressList, tokenAmountList, lockedPeriodList); } // distribution function distribution(address[] addressList, uint256[] tokenAmountList, uint256[] lockedPeriodList) onlyOwner internal { // Token allocation // - foundation : 25% // - platform ecosystem : 35% // - early investor : 12.5% // - private sale : 12.5% // - board of advisor : 10% // - bounty : 5% for (uint i = 0; i < addressList.length; i++) { uint256 lockedPeriod = lockedPeriodList[i]; // lock if (0 < lockedPeriod) { timeLock(addressList[i], tokenAmountList[i] * (10 ** uint256(decimals)), now + (lockedPeriod * 60 * 60 * 24)); } // unlock else { transfer(addressList[i], tokenAmountList[i] * (10 ** uint256(decimals))); } } } // lock modifier canTransfer(address _sender) { require(_sender != address(0)); require(canTransferIfLocked(_sender)); _; } function canTransferIfLocked(address _sender) internal view returns(bool) { if (0 == addressLocks[_sender]) return true; return (now >= addressLocks[_sender]); } function timeLock(address _to, uint256 _value, uint256 releaseDate) onlyOwner public { addressLocks[_to] = releaseDate; transfer(_to, _value); emit AddressLocked(_to, _value); } // erc20 methods function transfer(address _to, uint256 _value) canTransfer(msg.sender) whenNotPaused public returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from) whenNotPaused public returns (bool success) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) whenNotPaused public returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) whenNotPaused public returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) whenNotPaused public returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } // burn function burn(uint256 _value) onlyOwner public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } // token drain function emergencyERC20Drain(ERC20 token, uint256 amount) external onlyOwner { // owner can drain tokens that are sent here by mistake token.transfer(owner, amount); } }
distribution Token allocation - foundation : 25% - platform ecosystem : 35% - early investor : 12.5% - private sale : 12.5% - board of advisor : 10% - bounty : 5% lock unlock
function distribution(address[] addressList, uint256[] tokenAmountList, uint256[] lockedPeriodList) onlyOwner internal { for (uint i = 0; i < addressList.length; i++) { uint256 lockedPeriod = lockedPeriodList[i]; if (0 < lockedPeriod) { timeLock(addressList[i], tokenAmountList[i] * (10 ** uint256(decimals)), now + (lockedPeriod * 60 * 60 * 24)); } else { transfer(addressList[i], tokenAmountList[i] * (10 ** uint256(decimals))); } } }
912,361
./partial_match/11155111/0x37523dFFe2a485Afa8Ef662827acF9E835C040Bd/sources/Users/chichke/Documents/Work/Freelance/RealT/bridge-v2/contracts/operating/ComplianceRegistry.sol
Returns the CHF amount transfered (IN) by an address for a 31 days period for a specific realm _realm the realm for which we want the amount to be returned _trustedIntermediaries array of trustedIntermediaries in which we lookup the address _address address to lookup return the CHF amount transfered (IN) by an address for the period for a specific realm/
function monthlyInTransfers( address _realm, address[] calldata _trustedIntermediaries, address _address ) external override view returns (uint256) { return _monthlyInTransfers(_realm, _trustedIntermediaries, _address); }
3,536,135
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import {IEToken} from "../interfaces/IEToken.sol"; /** * @title DataTypes library * @dev Library with two EnumerableSet: * - ETokenToWadMap: enumerable mapping(EToken ==> amount) * - ETokenStatusMap: enumerable mapping(EToken ==> ETokenStatus) * @custom:security-contact [email protected] * @author Ensuro */ library DataTypes { using EnumerableSet for EnumerableSet.AddressSet; enum ETokenStatus { inactive, // doesn't exists - All operations rejected active, // deposit / withdraw / lockScr / unlockScr OK deprecated, // withdraw OK, unlockScr OK, deposit rejected, no new policies suspended // all operations temporarily rejected } // Copied from OpenZeppelin's EnumerableMap but with address as keys // and reimplemented with interfaces as keys // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // address keys and uint256 values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. struct Map { // Storage of keys EnumerableSet.AddressSet _keys; mapping(address => uint256) _values; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, address key, uint256 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, address key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, address key) private view returns (bool) { return map._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (address, uint256) { address key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, address key) private view returns (bool, uint256) { uint256 value = map._values[key]; if (value == 0) { return (_contains(map, key), 0); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, address key) private view returns (uint256) { uint256 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } // ETokenToWadMap struct ETokenToWadMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( ETokenToWadMap storage map, IEToken key, uint256 value ) internal returns (bool) { return _set(map._inner, address(key), value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(ETokenToWadMap storage map, IEToken key) internal returns (bool) { return _remove(map._inner, address(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(ETokenToWadMap storage map, IEToken key) internal view returns (bool) { return _contains(map._inner, address(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(ETokenToWadMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(ETokenToWadMap storage map, uint256 index) internal view returns (IEToken, uint256) { (address key, uint256 value) = _at(map._inner, index); return (IEToken(key), value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(ETokenToWadMap storage map, IEToken key) internal view returns (bool, uint256) { (bool success, uint256 value) = _tryGet(map._inner, address(key)); return (success, value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(ETokenToWadMap storage map, IEToken key) internal view returns (uint256) { return uint256(_get(map._inner, address(key))); } // ETokenStatusMap struct ETokenStatusMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( ETokenStatusMap storage map, IEToken key, ETokenStatus value ) internal returns (bool) { return _set(map._inner, address(key), uint256(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(ETokenStatusMap storage map, IEToken key) internal returns (bool) { return _remove(map._inner, address(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(ETokenStatusMap storage map, IEToken key) internal view returns (bool) { return _contains(map._inner, address(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(ETokenStatusMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(ETokenStatusMap storage map, uint256 index) internal view returns (IEToken, ETokenStatus) { (address key, uint256 value) = _at(map._inner, index); return (IEToken(key), ETokenStatus(value)); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(ETokenStatusMap storage map, IEToken key) internal view returns (bool, ETokenStatus) { (bool success, uint256 value) = _tryGet(map._inner, address(key)); return (success, ETokenStatus(value)); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(ETokenStatusMap storage map, IEToken key) internal view returns (ETokenStatus) { return ETokenStatus(_get(map._inner, address(key))); } }
Returns the number of elements in the map. O(1)./
function length(ETokenToWadMap storage map) internal view returns (uint256) { return _length(map._inner); }
2,551,093
./full_match/42/0x790b344f585FBebbB9FE3082cB6c25a4330a33bE/sources/tests/single_swap.sol
Transfer `amountIn` of DAI to this contract. Approve the router to spend DAI. Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps. The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools. Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).
function swapExactInputMultihop_SHIB_BNB(uint256 amountIn) external returns (uint256 amountOut) { TransferHelper.safeTransferFrom(SHIB, msg.sender, address(this), amountIn); TransferHelper.safeApprove(SHIB, address(swapRouter), amountIn); ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams({ path: abi.encodePacked(SHIB, poolFee, WETH9, poolFee,BNB ), recipient: msg.sender, deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: 0 }); }
16,279,048
// File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/CryptoRick.sol pragma solidity ^0.7.0; /** * @title CryptoRick contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract CryptoRick is ERC721, Ownable { using SafeMath for uint256; string public RICK_PROVENANCE = ""; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public constant rickPrice = 50000000000000000; //0.05 ETH uint public constant maxRickPurchase = 5; uint256 public MAX_RICK; bool public saleIsActive = false; uint256 public REVEAL_TIMESTAMP; constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 saleStart) ERC721(name, symbol) { MAX_RICK = maxNftSupply; REVEAL_TIMESTAMP = saleStart + (90000 * 9); } address[] withdrawAddresses = [0x3DcCb509199B52C21f60489D421080eA9167674D, 0xADDaF99990b665D8553f08653966fa8995Cc1209]; uint256[] withdrawPercents = [90, 10]; // Withdraw function sends the ETH to multiple addresses divided by percentages. function withdrawAll() public onlyOwner { uint256 contractBalance = address(this).balance; for(uint256 i=0;i<withdrawAddresses.length;i++) { uint256 amount = contractBalance * withdrawPercents[i] / 100; require(payable(withdrawAddresses[i]).send(amount)); } } /** * Set some Ricks aside */ function reserveRick() public onlyOwner { uint supply = totalSupply(); uint i; for (i = 0; i < 30; i++) { _safeMint(msg.sender, supply + i); } } /** * CryptoRick NFTs. */ function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner { REVEAL_TIMESTAMP = revealTimeStamp; } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory provenanceHash) public onlyOwner { RICK_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /* * Pause sale if active, make active if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } /** * Mints CryptoRick */ function mintRick(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Ricks"); require(numberOfTokens <= maxRickPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_RICK, "Purchase would exceed max supply of Ricks"); require(rickPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_RICK) { _safeMint(msg.sender, mintIndex); } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_RICK || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * Set the starting index for the collection */ function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_RICK; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_RICK; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function emergencySetStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } }
Mints CryptoRick/ If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block
function mintRick(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Ricks"); require(numberOfTokens <= maxRickPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_RICK, "Purchase would exceed max supply of Ricks"); require(rickPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_RICK) { _safeMint(msg.sender, mintIndex); } } if (startingIndexBlock == 0 && (totalSupply() == MAX_RICK || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } }
1,634,482
/** * Copyright 2017-2020, bZeroX, LLC <https://bzx.network/>. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library MathUtil { /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return divCeil(a, b, "SafeMath: division by zero"); } /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b != 0, errorMessage); if (a == 0) { return 0; } uint256 c = ((a - 1) / b) + 1; return c; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } interface IPriceFeeds { function queryRate( address sourceToken, address destToken) external view returns (uint256 rate, uint256 precision); function queryPrecision( address sourceToken, address destToken) external view returns (uint256 precision); function queryReturn( address sourceToken, address destToken, uint256 sourceAmount) external view returns (uint256 destAmount); function checkPriceDisagreement( address sourceToken, address destToken, uint256 sourceAmount, uint256 destAmount, uint256 maxSlippage) external view returns (uint256 sourceToDestSwapRate); function amountInEth( address Token, uint256 amount) external view returns (uint256 ethAmount); function getMaxDrawdown( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (uint256); function getCurrentMarginAndCollateralSize( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralInEthAmount); function getCurrentMargin( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralToLoanRate); function shouldLiquidate( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (bool); function getFastGasPrice( address payToken) external view returns (uint256); } contract IVestingToken is IERC20 { function claim() external; function vestedBalanceOf( address _owner) external view returns (uint256); function claimedBalanceOf( address _owner) external view returns (uint256); } /** * @dev Library for managing loan sets * * 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. * * Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`. * */ library EnumerableBytes32Set { struct Bytes32Set { // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) index; bytes32[] values; } /** * @dev Add an address value to a set. O(1). * Returns false if the value was already in the set. */ function addAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return addBytes32(set, value); } /** * @dev Add a value to a set. O(1). * Returns false if the value was already in the set. */ function addBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (!contains(set, value)){ set.index[value] = set.values.push(value); return true; } else { return false; } } /** * @dev Removes an address value from a set. O(1). * Returns false if the value was not present in the set. */ function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return removeBytes32(set, value); } /** * @dev Removes a value from a set. O(1). * Returns false if the value was not present in the set. */ function removeBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (contains(set, value)){ uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; // If the element we're deleting is the last one, we can just remove it without doing a swap if (lastIndex != toDeleteIndex) { bytes32 lastValue = set.values[lastIndex]; // Move the last value to the index where the deleted value is set.values[toDeleteIndex] = lastValue; // Update the index for the moved value set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the index entry for the deleted value delete set.index[value]; // Delete the old entry for the moved value set.values.pop(); return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return set.index[value] != 0; } /** * @dev Returns true if the value is in the set. O(1). */ function containsAddress(Bytes32Set storage set, address addrvalue) internal view returns (bool) { bytes32 value; assembly { value := addrvalue } return set.index[value] != 0; } /** * @dev Returns an array with all values in the set. O(N). * 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. * WARNING: This function may run out of gas on large sets: use {length} and * {get} instead in these cases. */ function enumerate(Bytes32Set storage set, uint256 start, uint256 count) internal view returns (bytes32[] memory output) { uint256 end = start + count; require(end >= start, "addition overflow"); end = set.values.length < end ? set.values.length : end; if (end == 0 || start >= end) { return output; } output = new bytes32[](end-start); for (uint256 i = start; i < end; i++) { output[i-start] = set.values[i]; } return output; } /** * @dev Returns the number of elements on the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return set.values.length; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function get(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return set.values[index]; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function getAddress(Bytes32Set storage set, uint256 index) internal view returns (address) { bytes32 value = set.values[index]; address addrvalue; assembly { addrvalue := value } return addrvalue; } } interface IUniswapV2Router { // 0x38ed1739 function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); // 0x8803dbee function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); // 0x1f00ca74 function getAmountsIn( uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); // 0xd06ca61f function getAmountsOut( uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } interface ICurve3Pool { function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount) external; function get_virtual_price() external view returns (uint256); } //0xd061D61a4d941c39E5453435B6345Dc261C2fcE0 eth mainnet interface ICurveMinter { function mint( address _addr ) external; } //0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A eth mainnet interface ICurve3PoolGauge { function balanceOf( address _addr ) external view returns (uint256); function working_balances(address) external view returns (uint256); function claimable_tokens(address) external returns (uint256); function deposit( uint256 _amount ) external; function deposit( uint256 _amount, address _addr ) external; function withdraw( uint256 _amount ) external; function set_approve_deposit( address _addr, bool can_deposit ) external; } /// @title A proxy interface for The Protocol /// @author bZeroX /// @notice This is just an interface, not to be deployed itself. /// @dev This interface is to be used for the protocol interactions. interface IBZx { ////// Protocol ////// /// @dev adds or replaces existing proxy module /// @param target target proxy module address function replaceContract(address target) external; /// @dev updates all proxy modules addreses and function signatures. /// sigsArr and targetsArr should be of equal length /// @param sigsArr array of function signatures /// @param targetsArr array of target proxy module addresses function setTargets( string[] calldata sigsArr, address[] calldata targetsArr ) external; /// @dev returns protocol module address given a function signature /// @return module address function getTarget(string calldata sig) external view returns (address); ////// Protocol Settings ////// /// @dev sets price feed contract address. The contract on the addres should implement IPriceFeeds interface /// @param newContract module address for the IPriceFeeds implementation function setPriceFeedContract(address newContract) external; /// @dev sets swaps contract address. The contract on the addres should implement ISwapsImpl interface /// @param newContract module address for the ISwapsImpl implementation function setSwapsImplContract(address newContract) external; /// @dev sets loan pool with assets. Accepts two arrays of equal length /// @param pools array of address of pools /// @param assets array of addresses of assets function setLoanPool(address[] calldata pools, address[] calldata assets) external; /// @dev updates list of supported tokens, it can be use also to disable or enable particualr token /// @param addrs array of address of pools /// @param toggles array of addresses of assets /// @param withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.) function setSupportedTokens( address[] calldata addrs, bool[] calldata toggles, bool withApprovals ) external; /// @dev sets lending fee with WEI_PERCENT_PRECISION /// @param newValue lending fee percent function setLendingFeePercent(uint256 newValue) external; /// @dev sets trading fee with WEI_PERCENT_PRECISION /// @param newValue trading fee percent function setTradingFeePercent(uint256 newValue) external; /// @dev sets borrowing fee with WEI_PERCENT_PRECISION /// @param newValue borrowing fee percent function setBorrowingFeePercent(uint256 newValue) external; /// @dev sets affiliate fee with WEI_PERCENT_PRECISION /// @param newValue affiliate fee percent function setAffiliateFeePercent(uint256 newValue) external; /// @dev sets liquidation inncetive percent per loan per token. This is the profit percent /// that liquidator gets in the process of liquidating. /// @param loanTokens array list of loan tokens /// @param collateralTokens array list of collateral tokens /// @param amounts array list of liquidation inncetive amount function setLiquidationIncentivePercent( address[] calldata loanTokens, address[] calldata collateralTokens, uint256[] calldata amounts ) external; /// @dev sets max swap rate slippage percent. /// @param newAmount max swap rate slippage percent. function setMaxDisagreement(uint256 newAmount) external; /// TODO function setSourceBufferPercent(uint256 newAmount) external; /// @dev sets maximum supported swap size in ETH /// @param newAmount max swap size in ETH. function setMaxSwapSize(uint256 newAmount) external; /// @dev sets fee controller address /// @param newController address of the new fees controller function setFeesController(address newController) external; /// @dev withdraws lending fees to receiver. Only can be called by feesController address /// @param tokens array of token addresses. /// @param receiver fees receiver address /// @return amounts array of amounts withdrawn function withdrawFees( address[] calldata tokens, address receiver, FeeClaimType feeType ) external returns (uint256[] memory amounts); /// @dev withdraw protocol token (BZRX) from vesting contract vBZRX /// @param receiver address of BZRX tokens claimed /// @param amount of BZRX token to be claimed. max is claimed if amount is greater than balance. /// @return rewardToken reward token address /// @return withdrawAmount amount function withdrawProtocolToken(address receiver, uint256 amount) external returns (address rewardToken, uint256 withdrawAmount); /// @dev depozit protocol token (BZRX) /// @param amount address of BZRX tokens to deposit function depositProtocolToken(uint256 amount) external; function grantRewards(address[] calldata users, uint256[] calldata amounts) external returns (uint256 totalAmount); // NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicates tokens input function queryFees(address[] calldata tokens, FeeClaimType feeType) external view returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid); function priceFeeds() external view returns (address); function swapsImpl() external view returns (address); function logicTargets(bytes4) external view returns (address); function loans(bytes32) external view returns (Loan memory); function loanParams(bytes32) external view returns (LoanParams memory); // we don't use this yet // function lenderOrders(address, bytes32) external returns (Order memory); // function borrowerOrders(address, bytes32) external returns (Order memory); function delegatedManagers(bytes32, address) external view returns (bool); function lenderInterest(address, address) external view returns (LenderInterest memory); function loanInterest(bytes32) external view returns (LoanInterest memory); function feesController() external view returns (address); function lendingFeePercent() external view returns (uint256); function lendingFeeTokensHeld(address) external view returns (uint256); function lendingFeeTokensPaid(address) external view returns (uint256); function borrowingFeePercent() external view returns (uint256); function borrowingFeeTokensHeld(address) external view returns (uint256); function borrowingFeeTokensPaid(address) external view returns (uint256); function protocolTokenHeld() external view returns (uint256); function protocolTokenPaid() external view returns (uint256); function affiliateFeePercent() external view returns (uint256); function liquidationIncentivePercent(address, address) external view returns (uint256); function loanPoolToUnderlying(address) external view returns (address); function underlyingToLoanPool(address) external view returns (address); function supportedTokens(address) external view returns (bool); function maxDisagreement() external view returns (uint256); function sourceBufferPercent() external view returns (uint256); function maxSwapSize() external view returns (uint256); /// @dev get list of loan pools in the system. Ordering is not guaranteed /// @param start start index /// @param count number of pools to return /// @return loanPoolsList array of loan pools function getLoanPoolsList(uint256 start, uint256 count) external view returns (address[] memory loanPoolsList); /// @dev checks whether addreess is a loan pool address /// @return boolean function isLoanPool(address loanPool) external view returns (bool); ////// Loan Settings ////// /// @dev creates new loan param settings /// @param loanParamsList array of LoanParams /// @return loanParamsIdList array of loan ids created function setupLoanParams(LoanParams[] calldata loanParamsList) external returns (bytes32[] memory loanParamsIdList); /// @dev Deactivates LoanParams for future loans. Active loans using it are unaffected. /// @param loanParamsIdList array of loan ids function disableLoanParams(bytes32[] calldata loanParamsIdList) external; /// @dev gets array of LoanParams by given ids /// @param loanParamsIdList array of loan ids /// @return loanParamsList array of LoanParams function getLoanParams(bytes32[] calldata loanParamsIdList) external view returns (LoanParams[] memory loanParamsList); /// @dev Enumerates LoanParams in the system by owner /// @param owner of the loan params /// @param start number of loans to return /// @param count total number of the items /// @return loanParamsList array of LoanParams function getLoanParamsList( address owner, uint256 start, uint256 count ) external view returns (bytes32[] memory loanParamsList); /// @dev returns total loan principal for token address /// @param lender address /// @param loanToken address /// @return total principal of the loan function getTotalPrincipal(address lender, address loanToken) external view returns (uint256); ////// Loan Openings ////// /// @dev This is THE function that borrows or trades on the protocol /// @param loanParamsId id of the LoanParam created beforehand by setupLoanParams function /// @param loanId id of existing loan, if 0, start a new loan /// @param isTorqueLoan boolean whether it is toreque or non torque loan /// @param initialMargin in WEI_PERCENT_PRECISION /// @param sentAddresses array of size 4: /// lender: must match loan if loanId provided /// borrower: must match loan if loanId provided /// receiver: receiver of funds (address(0) assumes borrower address) /// manager: delegated manager of loan unless address(0) /// @param sentValues array of size 5: /// newRate: new loan interest rate /// newPrincipal: new loan size (borrowAmount + any borrowed interest) /// torqueInterest: new amount of interest to escrow for Torque loan (determines initial loan length) /// loanTokenReceived: total loanToken deposit (amount not sent to borrower in the case of Torque loans) /// collateralTokenReceived: total collateralToken deposit /// @param loanDataBytes required when sending ether /// @return principal of the loan and collateral amount function borrowOrTradeFromPool( bytes32 loanParamsId, bytes32 loanId, bool isTorqueLoan, uint256 initialMargin, address[4] calldata sentAddresses, uint256[5] calldata sentValues, bytes calldata loanDataBytes ) external payable returns (LoanOpenData memory); /// @dev sets/disables/enables the delegated manager for the loan /// @param loanId id of the loan /// @param delegated delegated manager address /// @param toggle boolean set enabled or disabled function setDelegatedManager( bytes32 loanId, address delegated, bool toggle ) external; /// @dev estimates margin exposure for simulated position /// @param loanToken address of the loan token /// @param collateralToken address of collateral token /// @param loanTokenSent amout of loan token sent /// @param collateralTokenSent amount of collateral token sent /// @param interestRate yearly interest rate /// @param newPrincipal principal amount of the loan /// @return estimated margin exposure amount function getEstimatedMarginExposure( address loanToken, address collateralToken, uint256 loanTokenSent, uint256 collateralTokenSent, uint256 interestRate, uint256 newPrincipal ) external view returns (uint256); /// @dev calculates required collateral for simulated position /// @param loanToken address of loan token /// @param collateralToken address of collateral token /// @param newPrincipal principal amount of the loan /// @param marginAmount margin amount of the loan /// @param isTorqueLoan boolean torque or non torque loan /// @return collateralAmountRequired amount required function getRequiredCollateral( address loanToken, address collateralToken, uint256 newPrincipal, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 collateralAmountRequired); function getRequiredCollateralByParams( bytes32 loanParamsId, uint256 newPrincipal ) external view returns (uint256 collateralAmountRequired); /// @dev calculates borrow amount for simulated position /// @param loanToken address of loan token /// @param collateralToken address of collateral token /// @param collateralTokenAmount amount of collateral token sent /// @param marginAmount margin amount /// @param isTorqueLoan boolean torque or non torque loan /// @return borrowAmount possible borrow amount function getBorrowAmount( address loanToken, address collateralToken, uint256 collateralTokenAmount, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 borrowAmount); function getBorrowAmountByParams( bytes32 loanParamsId, uint256 collateralTokenAmount ) external view returns (uint256 borrowAmount); ////// Loan Closings ////// /// @dev liquidates unhealty loans /// @param loanId id of the loan /// @param receiver address receiving liquidated loan collateral /// @param closeAmount amount to close denominated in loanToken /// @return loanCloseAmount amount of the collateral token of the loan /// @return seizedAmount sezied amount in the collateral token /// @return seizedToken loan token address function liquidate( bytes32 loanId, address receiver, uint256 closeAmount ) external payable returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ); /// @dev rollover loan /// @param loanId id of the loan /// @param loanDataBytes reserved for future use. function rollover(bytes32 loanId, bytes calldata loanDataBytes) external returns (address rebateToken, uint256 gasRebate); /// @dev close position with loan token deposit /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param depositAmount amount of loan token to deposit /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithDeposit( bytes32 loanId, address receiver, uint256 depositAmount // denominated in loanToken ) external payable returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); /// @dev close position with swap /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param swapAmount amount of loan token to swap /// @param returnTokenIsCollateral boolean whether to return tokens is collateral /// @param loanDataBytes reserved for future use /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithSwap( bytes32 loanId, address receiver, uint256 swapAmount, // denominated in collateralToken bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken bytes calldata loanDataBytes ) external returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); ////// Loan Closings With Gas Token ////// /// @dev liquidates unhealty loans by using Gas token /// @param loanId id of the loan /// @param receiver address receiving liquidated loan collateral /// @param gasTokenUser user address of the GAS token /// @param closeAmount amount to close denominated in loanToken /// @return loanCloseAmount loan close amount /// @return seizedAmount loan token withdraw amount /// @return seizedToken loan token address function liquidateWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 closeAmount // denominated in loanToken ) external payable returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ); /// @dev rollover loan /// @param loanId id of the loan /// @param gasTokenUser user address of the GAS token function rolloverWithGasToken( bytes32 loanId, address gasTokenUser, bytes calldata /*loanDataBytes*/ ) external returns (address rebateToken, uint256 gasRebate); /// @dev close position with loan token deposit /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param gasTokenUser user address of the GAS token /// @param depositAmount amount of loan token to deposit denominated in loanToken /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithDepositWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 depositAmount ) external payable returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); /// @dev close position with swap /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param gasTokenUser user address of the GAS token /// @param swapAmount amount of loan token to swap denominated in collateralToken /// @param returnTokenIsCollateral true: withdraws collateralToken, false: withdraws loanToken /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithSwapWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 swapAmount, bool returnTokenIsCollateral, bytes calldata loanDataBytes ) external returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); ////// Loan Maintenance ////// /// @dev deposit collateral to existing loan /// @param loanId existing loan id /// @param depositAmount amount to deposit which must match msg.value if ether is sent function depositCollateral(bytes32 loanId, uint256 depositAmount) external payable; /// @dev withdraw collateral from existing loan /// @param loanId existing lona id /// @param receiver address of withdrawn tokens /// @param withdrawAmount amount to withdraw /// @return actualWithdrawAmount actual amount withdrawn function withdrawCollateral( bytes32 loanId, address receiver, uint256 withdrawAmount ) external returns (uint256 actualWithdrawAmount); /// @dev withdraw accrued interest rate for a loan given token address /// @param loanToken loan token address function withdrawAccruedInterest(address loanToken) external; /// @dev extends loan duration by depositing more collateral /// @param loanId id of the existing loan /// @param depositAmount amount to deposit /// @param useCollateral boolean whether to extend using collateral or deposit amount /// @return secondsExtended by that number of seconds loan duration was extended function extendLoanDuration( bytes32 loanId, uint256 depositAmount, bool useCollateral, bytes calldata // for future use /*loanDataBytes*/ ) external payable returns (uint256 secondsExtended); /// @dev reduces loan duration by withdrawing collateral /// @param loanId id of the existing loan /// @param receiver address to receive tokens /// @param withdrawAmount amount to withdraw /// @return secondsReduced by that number of seconds loan duration was extended function reduceLoanDuration( bytes32 loanId, address receiver, uint256 withdrawAmount ) external returns (uint256 secondsReduced); function setDepositAmount( bytes32 loanId, uint256 depositValueAsLoanToken, uint256 depositValueAsCollateralToken ) external; function claimRewards(address receiver) external returns (uint256 claimAmount); function transferLoan(bytes32 loanId, address newOwner) external; function rewardsBalanceOf(address user) external view returns (uint256 rewardsBalance); /// @dev Gets current lender interest data totals for all loans with a specific oracle and interest token /// @param lender The lender address /// @param loanToken The loan token address /// @return interestPaid The total amount of interest that has been paid to a lender so far /// @return interestPaidDate The date of the last interest pay out, or 0 if no interest has been withdrawn yet /// @return interestOwedPerDay The amount of interest the lender is earning per day /// @return interestUnPaid The total amount of interest the lender is owned and not yet withdrawn /// @return interestFeePercent The fee retained by the protocol before interest is paid to the lender /// @return principalTotal The total amount of outstading principal the lender has loaned function getLenderInterestData(address lender, address loanToken) external view returns ( uint256 interestPaid, uint256 interestPaidDate, uint256 interestOwedPerDay, uint256 interestUnPaid, uint256 interestFeePercent, uint256 principalTotal ); /// @dev Gets current interest data for a loan /// @param loanId A unique id representing the loan /// @return loanToken The loan token that interest is paid in /// @return interestOwedPerDay The amount of interest the borrower is paying per day /// @return interestDepositTotal The total amount of interest the borrower has deposited /// @return interestDepositRemaining The amount of deposited interest that is not yet owed to a lender function getLoanInterestData(bytes32 loanId) external view returns ( address loanToken, uint256 interestOwedPerDay, uint256 interestDepositTotal, uint256 interestDepositRemaining ); /// @dev gets list of loans of particular user address /// @param user address of the loans /// @param start of the index /// @param count number of loans to return /// @param loanType type of the loan: All(0), Margin(1), NonMargin(2) /// @param isLender whether to list lender loans or borrower loans /// @param unsafeOnly booleat if true return only unsafe loans that are open for liquidation /// @return loansData LoanReturnData array of loans function getUserLoans( address user, uint256 start, uint256 count, LoanType loanType, bool isLender, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData); function getUserLoansCount(address user, bool isLender) external view returns (uint256); /// @dev gets existing loan /// @param loanId id of existing loan /// @return loanData array of loans function getLoan(bytes32 loanId) external view returns (LoanReturnData memory loanData); /// @dev get current active loans in the system /// @param start of the index /// @param count number of loans to return /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation) function getActiveLoans( uint256 start, uint256 count, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData); /// @dev get current active loans in the system /// @param start of the index /// @param count number of loans to return /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation) /// @param isLiquidatable boolean if true return liquidatable loans only function getActiveLoansAdvanced( uint256 start, uint256 count, bool unsafeOnly, bool isLiquidatable ) external view returns (LoanReturnData[] memory loansData); function getActiveLoansCount() external view returns (uint256); ////// Swap External ////// /// @dev swap thru external integration /// @param sourceToken source token address /// @param destToken destintaion token address /// @param receiver address to receive tokens /// @param returnToSender TODO /// @param sourceTokenAmount source token amount /// @param requiredDestTokenAmount destination token amount /// @param swapData TODO /// @return destTokenAmountReceived destination token received /// @return sourceTokenAmountUsed source token amount used function swapExternal( address sourceToken, address destToken, address receiver, address returnToSender, uint256 sourceTokenAmount, uint256 requiredDestTokenAmount, bytes calldata swapData ) external payable returns ( uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed ); /// @dev swap thru external integration using GAS /// @param sourceToken source token address /// @param destToken destintaion token address /// @param receiver address to receive tokens /// @param returnToSender TODO /// @param gasTokenUser user address of the GAS token /// @param sourceTokenAmount source token amount /// @param requiredDestTokenAmount destination token amount /// @param swapData TODO /// @return destTokenAmountReceived destination token received /// @return sourceTokenAmountUsed source token amount used function swapExternalWithGasToken( address sourceToken, address destToken, address receiver, address returnToSender, address gasTokenUser, uint256 sourceTokenAmount, uint256 requiredDestTokenAmount, bytes calldata swapData ) external payable returns ( uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed ); /// @dev calculate simulated return of swap /// @param sourceToken source token address /// @param destToken destination token address /// @param sourceTokenAmount source token amount /// @return amoun denominated in destination token function getSwapExpectedReturn( address sourceToken, address destToken, uint256 sourceTokenAmount ) external view returns (uint256); function owner() external view returns (address); function transferOwnership(address newOwner) external; /// Guardian Interface function _isPaused(bytes4 sig) external view returns (bool isPaused); function toggleFunctionPause(bytes4 sig) external; function toggleFunctionUnPause(bytes4 sig) external; function changeGuardian(address newGuardian) external; function getGuardian() external view returns (address guardian); /// Loan Cleanup Interface function cleanupLoans( address loanToken, bytes32[] calldata loanIds) external payable returns (uint256 totalPrincipalIn); struct LoanParams { bytes32 id; bool active; address owner; address loanToken; address collateralToken; uint256 minInitialMargin; uint256 maintenanceMargin; uint256 maxLoanTerm; } struct LoanOpenData { bytes32 loanId; uint256 principal; uint256 collateral; } enum LoanType { All, Margin, NonMargin } struct LoanReturnData { bytes32 loanId; uint96 endTimestamp; address loanToken; address collateralToken; uint256 principal; uint256 collateral; uint256 interestOwedPerDay; uint256 interestDepositRemaining; uint256 startRate; uint256 startMargin; uint256 maintenanceMargin; uint256 currentMargin; uint256 maxLoanTerm; uint256 maxLiquidatable; uint256 maxSeizable; uint256 depositValueAsLoanToken; uint256 depositValueAsCollateralToken; } enum FeeClaimType { All, Lending, Trading, Borrowing } struct Loan { bytes32 id; // id of the loan bytes32 loanParamsId; // the linked loan params id bytes32 pendingTradesId; // the linked pending trades id uint256 principal; // total borrowed amount outstanding uint256 collateral; // total collateral escrowed for the loan uint256 startTimestamp; // loan start time uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time uint256 startMargin; // initial margin when the loan opened uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken address borrower; // borrower of this loan address lender; // lender of this loan bool active; // if false, the loan has been fully closed } struct LenderInterest { uint256 principalTotal; // total borrowed amount outstanding of asset uint256 owedPerDay; // interest owed per day for all loans of asset uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term) uint256 paidTotal; // total interest paid so far for asset uint256 updatedTimestamp; // last update } struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan uint256 depositTotal; // total escrowed interest for loan uint256 updatedTimestamp; // last update } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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; } } interface IMasterChefSushi { struct UserInfo { uint256 amount; uint256 rewardDebt; } function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; // Info of each user that stakes LP tokens. function userInfo(uint256, address) external view returns (UserInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); } interface IStaking { struct ProposalState { uint256 proposalTime; uint256 iBZRXWeight; uint256 lpBZRXBalance; uint256 lpTotalSupply; } struct AltRewardsUserInfo { uint256 rewardsPerShare; uint256 pendingRewards; } function getCurrentFeeTokens() external view returns (address[] memory); function maxUniswapDisagreement() external view returns (uint256); function isPaused() external view returns (bool); function fundsWallet() external view returns (address); function callerRewardDivisor() external view returns (uint256); function maxCurveDisagreement() external view returns (uint256); function rewardPercent() external view returns (uint256); function addRewards(uint256 newBZRX, uint256 newStableCoin) external; function stake( address[] calldata tokens, uint256[] calldata values ) external; function unstake( address[] calldata tokens, uint256[] calldata values ) external; function earned(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function pendingCrvRewards(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function getVariableWeights() external view returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight); function balanceOfByAsset( address token, address account) external view returns (uint256 balance); function balanceOfByAssets( address account) external view returns ( uint256 bzrxBalance, uint256 iBZRXBalance, uint256 vBZRXBalance, uint256 LPTokenBalance, uint256 LPTokenBalanceOld ); function balanceOfStored( address account) external view returns (uint256 vestedBalance, uint256 vestingBalance); function totalSupplyStored() external view returns (uint256 supply); function vestedBalanceForAmount( uint256 tokenBalance, uint256 lastUpdate, uint256 vestingEndTime) external view returns (uint256 vested); function votingBalanceOf( address account, uint256 proposalId) external view returns (uint256 totalVotes); function votingBalanceOfNow( address account) external view returns (uint256 totalVotes); function votingFromStakedBalanceOf( address account) external view returns (uint256 totalVotes); function _setProposalVals( address account, uint256 proposalId) external returns (uint256); function exit() external; function addAltRewards(address token, uint256 amount) external; function governor() external view returns(address); } contract StakingConstants { address public constant BZRX = 0x56d811088235F11C8920698a204A5010a788f4b3; address public constant vBZRX = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; address public constant iBZRX = 0x18240BD9C07fA6156Ce3F3f61921cC82b2619157; address public constant LPToken = 0xa30911e072A0C88D55B5D0A0984B66b0D04569d0; // sushiswap address public constant LPTokenOld = 0xe26A220a341EAca116bDa64cF9D5638A935ae629; // balancer IERC20 public constant curve3Crv = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant SUSHI = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; IUniswapV2Router public constant uniswapRouter = IUniswapV2Router(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // sushiswap ICurve3Pool public constant curve3pool = ICurve3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); IBZx public constant bZx = IBZx(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f); uint256 public constant cliffDuration = 15768000; // 86400 * 365 * 0.5 uint256 public constant vestingDuration = 126144000; // 86400 * 365 * 4 uint256 internal constant vestingDurationAfterCliff = 110376000; // 86400 * 365 * 3.5 uint256 internal constant vestingStartTimestamp = 1594648800; // start_time uint256 internal constant vestingCliffTimestamp = vestingStartTimestamp + cliffDuration; uint256 internal constant vestingEndTimestamp = vestingStartTimestamp + vestingDuration; uint256 internal constant _startingVBZRXBalance = 889389933e18; // 889,389,933 BZRX address internal constant SUSHI_MASTERCHEF = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; uint256 internal constant BZRX_ETH_SUSHI_MASTERCHEF_PID = 188; uint256 public constant BZRXWeightStored = 1e18; ICurveMinter public constant curveMinter = ICurveMinter(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); ICurve3PoolGauge public constant curve3PoolGauge = ICurve3PoolGauge(0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A); address public constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; struct DelegatedTokens { address user; uint256 BZRX; uint256 vBZRX; uint256 iBZRX; uint256 LPToken; uint256 totalVotes; } event Stake( address indexed user, address indexed token, address indexed delegate, uint256 amount ); event Unstake( address indexed user, address indexed token, address indexed delegate, uint256 amount ); event AddRewards( address indexed sender, uint256 bzrxAmount, uint256 stableCoinAmount ); event Claim( address indexed user, uint256 bzrxAmount, uint256 stableCoinAmount ); event ChangeDelegate( address indexed user, address indexed oldDelegate, address indexed newDelegate ); event WithdrawFees( address indexed sender ); event ConvertFees( address indexed sender, uint256 bzrxOutput, uint256 stableCoinOutput ); event DistributeFees( address indexed sender, uint256 bzrxRewards, uint256 stableCoinRewards ); event AddAltRewards( address indexed sender, address indexed token, uint256 amount ); event ClaimAltRewards( address indexed user, address indexed token, uint256 amount ); } contract StakingUpgradeable is Ownable { address public implementation; } contract StakingState is StakingUpgradeable { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; uint256 public constant initialCirculatingSupply = 1030000000e18 - 889389933e18; address internal constant ZERO_ADDRESS = address(0); bool public isPaused; address public fundsWallet; mapping(address => uint256) internal _totalSupplyPerToken; // token => value mapping(address => mapping(address => uint256)) internal _balancesPerToken; // token => account => value mapping(address => address) internal delegate; // user => delegate (DEPRECIATED) mapping(address => mapping(address => uint256)) internal delegatedPerToken; // token => user => value (DEPRECIATED) uint256 public bzrxPerTokenStored; mapping(address => uint256) public bzrxRewardsPerTokenPaid; // user => value mapping(address => uint256) public bzrxRewards; // user => value mapping(address => uint256) public bzrxVesting; // user => value uint256 public stableCoinPerTokenStored; mapping(address => uint256) public stableCoinRewardsPerTokenPaid; // user => value mapping(address => uint256) public stableCoinRewards; // user => value mapping(address => uint256) public stableCoinVesting; // user => value uint256 public vBZRXWeightStored; uint256 public iBZRXWeightStored; uint256 public LPTokenWeightStored; EnumerableBytes32Set.Bytes32Set internal _delegatedSet; uint256 public lastRewardsAddTime; mapping(address => uint256) public vestingLastSync; mapping(address => address[]) public swapPaths; mapping(address => uint256) public stakingRewards; uint256 public rewardPercent = 50e18; uint256 public maxUniswapDisagreement = 3e18; uint256 public maxCurveDisagreement = 3e18; uint256 public callerRewardDivisor = 100; address[] public currentFeeTokens; struct ProposalState { uint256 proposalTime; uint256 iBZRXWeight; uint256 lpBZRXBalance; uint256 lpTotalSupply; } address public governor; mapping(uint256 => ProposalState) internal _proposalState; mapping(address => uint256[]) public altRewardsRounds; // depreciated mapping(address => uint256) public altRewardsPerShare; // token => value // Token => (User => Info) mapping(address => mapping(address => IStaking.AltRewardsUserInfo)) public userAltRewardsPerShare; address public voteDelegator; } contract PausableGuardian is Ownable { // keccak256("Pausable_FunctionPause") bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047; // keccak256("Pausable_GuardianAddress") bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf; modifier pausable { require(!_isPaused(msg.sig), "paused"); _; } function _isPaused(bytes4 sig) public view returns (bool isPaused) { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { isPaused := sload(slot) } } function toggleFunctionPause(bytes4 sig) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 1) } } function toggleFunctionUnPause(bytes4 sig) public { // only DAO can unpause, and adding guardian temporarily require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 0) } } function changeGuardian(address newGuardian) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); assembly { sstore(Pausable_GuardianAddress, newGuardian) } } function getGuardian() public view returns (address guardian) { assembly { guardian := sload(Pausable_GuardianAddress) } } } contract GovernorBravoEvents { /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal /// @param voter The address which casted a vote /// @param proposalId The proposal id which was voted on /// @param support Support value for the vote. 0=against, 1=for, 2=abstain /// @param votes Number of votes which were cast by the voter /// @param reason The reason given for the vote by the voter event VoteCast(address indexed voter, uint proposalId, uint8 support, uint votes, string reason); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); /// @notice An event emitted when the voting delay is set event VotingDelaySet(uint oldVotingDelay, uint newVotingDelay); /// @notice An event emitted when the voting period is set event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod); /// @notice Emitted when implementation is changed event NewImplementation(address oldImplementation, address newImplementation); /// @notice Emitted when proposal threshold is set event ProposalThresholdSet(uint oldProposalThreshold, uint newProposalThreshold); /// @notice Emitted when pendingAdmin is changed event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /// @notice Emitted when pendingAdmin is accepted, which means admin is updated event NewAdmin(address oldAdmin, address newAdmin); } contract GovernorBravoDelegatorStorage { /// @notice Administrator for this contract address public admin; /// @notice Pending administrator for this contract address public pendingAdmin; /// @notice Active brains of Governor address public implementation; /// @notice The address of the Governor Guardian address public guardian; } /** * @title Storage for Governor Bravo Delegate * @notice For future upgrades, do not change GovernorBravoDelegateStorageV1. Create a new * contract which implements GovernorBravoDelegateStorageV1 and following the naming convention * GovernorBravoDelegateStorageVX. */ contract GovernorBravoDelegateStorageV1 is GovernorBravoDelegatorStorage { /// @notice The delay before voting on a proposal may take place, once proposed, in blocks uint public votingDelay; /// @notice The duration of voting on a proposal, in blocks uint public votingPeriod; /// @notice The number of votes required in order for a voter to become a proposer uint public proposalThreshold; /// @notice Initial proposal id set at become uint public initialProposalId; /// @notice The total number of proposals uint public proposalCount; /// @notice The address of the bZx Protocol Timelock TimelockInterface public timelock; /// @notice The address of the bZx governance token StakingInterface public staking; /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; struct Proposal { /// @notice Unique id for looking up a proposal uint id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; /// @notice Current number of votes in favor of this proposal uint forVotes; /// @notice Current number of votes in opposition to this proposal uint againstVotes; /// @notice Current number of votes for abstaining for this proposal uint abstainVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal or abstains uint8 support; /// @notice The number of votes the voter had, which were cast uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } interface TimelockInterface { function delay() external view returns (uint); function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface StakingInterface { function votingBalanceOf( address account, uint proposalCount) external view returns (uint totalVotes); function votingBalanceOfNow( address account) external view returns (uint totalVotes); function _setProposalVals( address account, uint proposalCount) external returns (uint); } interface GovernorAlpha { /// @notice The total number of proposals function proposalCount() external returns (uint); } contract GovernorBravoDelegate is GovernorBravoDelegateStorageV1, GovernorBravoEvents { /// @notice The name of this contract string public constant name = "bZx Governor Bravo"; /// @notice The minimum setable proposal threshold uint public constant MIN_PROPOSAL_THRESHOLD = 5150000e18; // 5,150,000 = 0.5% of BZRX /// @notice The maximum setable proposal threshold uint public constant MAX_PROPOSAL_THRESHOLD = 20600000e18; // 20,600,000 = 2% of BZRX /// @notice The minimum setable voting period uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours /// @notice The max setable voting period uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks /// @notice The min setable voting delay uint public constant MIN_VOTING_DELAY = 1; /// @notice The max setable voting delay uint public constant MAX_VOTING_DELAY = 40320; // About 1 week /// @notice The maximum number of actions that can be included in a proposal uint public constant proposalMaxOperations = 100; // 100 actions /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); mapping (uint => uint) public quorumVotesForProposal; // proposalId => quorum votes required /** * @notice Used to initialize the contract during delegator contructor * @param timelock_ The address of the Timelock * @param staking_ The address of the STAKING * @param votingPeriod_ The initial voting period * @param votingDelay_ The initial voting delay * @param proposalThreshold_ The initial proposal threshold */ function initialize(address timelock_, address staking_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public { require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once"); require(msg.sender == admin, "GovernorBravo::initialize: admin only"); require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address"); require(staking_ != address(0), "GovernorBravo::initialize: invalid STAKING address"); require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period"); require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay"); require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold"); timelock = TimelockInterface(timelock_); staking = StakingInterface(staking_); votingPeriod = votingPeriod_; votingDelay = votingDelay_; proposalThreshold = proposalThreshold_; guardian = msg.sender; } /** * @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold * @param targets Target addresses for proposal calls * @param values Eth values for proposal calls * @param signatures Function signatures for proposal calls * @param calldatas Calldatas for proposal calls * @param description String description of the proposal * @return Proposal id of new proposal */ function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorBravo::propose: must provide actions"); require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal"); } uint proposalId = proposalCount + 1; require(staking._setProposalVals(msg.sender, proposalId) > proposalThreshold, "GovernorBravo::propose: proposer votes below proposal threshold"); proposalCount = proposalId; uint startBlock = add256(block.number, votingDelay); uint endBlock = add256(startBlock, votingPeriod); Proposal memory newProposal = Proposal({ id: proposalId, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, abstainVotes: 0, canceled: false, executed: false }); proposals[proposalId] = newProposal; latestProposalIds[msg.sender] = proposalId; quorumVotesForProposal[proposalId] = quorumVotes(); emit ProposalCreated(proposalId, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return proposalId; } /** * @notice Queues a proposal of state succeeded * @param proposalId The id of the proposal to queue */ function queue(uint proposalId) external { require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } /** * @notice Executes a queued proposal if eta has passed * @param proposalId The id of the proposal to execute */ function execute(uint proposalId) external payable { require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } /** * @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold * @param proposalId The id of the proposal to cancel */ function cancel(uint proposalId) external { require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == proposal.proposer || staking.votingBalanceOfNow(proposal.proposer) < proposalThreshold || msg.sender == guardian, "GovernorBravo::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } /** * @notice Gets the current voting quroum * @return The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed */ // TODO: Update for OOKI. Handle OOKI surplus mint function quorumVotes() public view returns (uint256) { uint256 vestingSupply = IERC20(0x56d811088235F11C8920698a204A5010a788f4b3) // BZRX .balanceOf(0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F); // vBZRX uint256 circulatingSupply = 1030000000e18 - vestingSupply; // no overflow uint256 quorum = circulatingSupply * 4 / 100; if (quorum < 15450000e18) { // min quorum is 1.5% of totalSupply quorum = 15450000e18; } return quorum; } /** * @notice Gets actions of a proposal * @param proposalId the id of the proposal * @return Targets, values, signatures, and calldatas of the proposal actions */ function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice Gets the receipt for a voter on a given proposal * @param proposalId the id of proposal * @param voter The address of the voter * @return The voting receipt */ function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } /** * @notice Gets the state of a proposal * @param proposalId The id of the proposal * @return Proposal state */ function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; 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 < quorumVotesForProposal[proposalId]) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } /** * @notice Cast a vote for a proposal * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain */ function castVote(uint proposalId, uint8 support) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), ""); } /** * @notice Cast a vote for a proposal with a reason * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @param reason The reason given for the vote by the voter */ function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason); } /** * @notice Cast a vote for a proposal by signature * @dev External function that accepts EIP-712 signatures for voting on proposals. */ function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature"); emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), ""); } /** * @dev Allows batching to castVote function */ function castVotes(uint[] calldata proposalIds, uint8[] calldata supportVals) external { require(proposalIds.length == supportVals.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), ""); } } /** * @dev Allows batching to castVoteWithReason function */ function castVotesWithReason(uint[] calldata proposalIds, uint8[] calldata supportVals, string[] calldata reasons) external { require(proposalIds.length == supportVals.length && proposalIds.length == reasons.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), reasons[i]); } } /** * @dev Allows batching to castVoteBySig function */ function castVotesBySig(uint[] calldata proposalIds, uint8[] calldata supportVals, uint8[] calldata vs, bytes32[] calldata rs, bytes32[] calldata ss) external { require(proposalIds.length == supportVals.length && proposalIds.length == vs.length && proposalIds.length == rs.length && proposalIds.length == ss.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { castVoteBySig(proposalIds[i], supportVals[i], vs[i], rs[i], ss[i]); } } /** * @notice Internal function that caries out voting logic * @param voter The voter that is casting their vote * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @return The number of votes cast */ function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) { require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed"); require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted"); // 2**96-1 is greater than total supply of bzrx 1.3b*1e18 thus guaranteeing it won't ever overflow uint96 votes = uint96(staking.votingBalanceOf(voter, proposalId)); if (support == 0) { proposal.againstVotes = add256(proposal.againstVotes, votes); } else if (support == 1) { proposal.forVotes = add256(proposal.forVotes, votes); } else if (support == 2) { proposal.abstainVotes = add256(proposal.abstainVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; return votes; } /** * @notice Admin function for setting the voting delay * @param newVotingDelay new voting delay, in blocks */ function __setVotingDelay(uint newVotingDelay) external { require(msg.sender == admin, "GovernorBravo::__setVotingDelay: admin only"); require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::__setVotingDelay: invalid voting delay"); uint oldVotingDelay = votingDelay; votingDelay = newVotingDelay; emit VotingDelaySet(oldVotingDelay,votingDelay); } /** * @notice Admin function for setting the voting period * @param newVotingPeriod new voting period, in blocks */ function __setVotingPeriod(uint newVotingPeriod) external { require(msg.sender == admin, "GovernorBravo::__setVotingPeriod: admin only"); require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::__setVotingPeriod: invalid voting period"); uint oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); } /** * @notice Admin function for setting the proposal threshold * @dev newProposalThreshold must be greater than the hardcoded min * @param newProposalThreshold new proposal threshold */ function __setProposalThreshold(uint newProposalThreshold) external { require(msg.sender == admin, "GovernorBravo::__setProposalThreshold: admin only"); require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::__setProposalThreshold: invalid proposal threshold"); uint oldProposalThreshold = proposalThreshold; proposalThreshold = newProposalThreshold; emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `__acceptLocalAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `__acceptLocalAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function __setPendingLocalAdmin(address newPendingAdmin) external { // Check caller = admin require(msg.sender == admin, "GovernorBravo:__setPendingLocalAdmin: admin only"); // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function __acceptLocalAdmin() external { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:__acceptLocalAdmin: pending admin only"); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } function __changeGuardian(address guardian_) public { require(msg.sender == guardian, "GovernorBravo::__changeGuardian: sender must be gov guardian"); require(guardian_ != address(0), "GovernorBravo::__changeGuardian: not allowed"); guardian = guardian_; } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorBravo::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorBravo::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorBravo::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorBravo::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainIdInternal() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } contract StakingVoteDelegatorState is StakingUpgradeable { // A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; } contract StakingVoteDelegatorConstants { address constant internal ZERO_ADDRESS = address(0); IStaking constant staking = IStaking(0xe95Ebce2B02Ee07dEF5Ed6B53289801F7Fc137A4); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); } contract StakingVoteDelegator is StakingVoteDelegatorState, StakingVoteDelegatorConstants { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { if(delegatee == ZERO_ADDRESS){ delegatee = msg.sender; } return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes("STAKING")), 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), "Staking::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Staking::delegateBySig: invalid nonce"); require(now <= expiry, "Staking::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint256) { require(blockNumber < block.number, "Staking::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = staking.votingFromStakedBalanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function moveDelegates(address srcRep, address dstRep, uint256 amount) public { require(msg.sender == address(staking), "unauthorized"); _moveDelegates(srcRep, dstRep, amount); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub((amount > srcRepOld)? srcRepOld : amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal { uint32 blockNumber = safe32(block.number, "Staking::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } contract StakingV1_1 is StakingState, StakingConstants, PausableGuardian { using MathUtil for uint256; modifier onlyEOA() { require(msg.sender == tx.origin, "unauthorized"); _; } function getCurrentFeeTokens() external view returns (address[] memory) { return currentFeeTokens; } function _pendingSushiRewards(address _user) internal view returns (uint256) { uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF) .pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this)); uint256 totalSupply = _totalSupplyPerToken[LPToken]; return _pendingAltRewards( SUSHI, _user, balanceOfByAsset(LPToken, _user), totalSupply != 0 ? pendingSushi.mul(1e12).div(totalSupply) : 0 ); } function pendingCrvRewards(address account) external returns(uint256){ (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned( account, bzrxPerTokenStored, stableCoinPerTokenStored ); (,stableCoinRewardsEarned) = _syncVesting( account, bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting ); return _pendingCrvRewards(account, stableCoinRewardsEarned); } function _pendingCrvRewards(address _user, uint256 stableCoinRewardsEarned) internal returns (uint256) { uint256 totalSupply = curve3PoolGauge.balanceOf(address(this)); uint256 pendingCrv = curve3PoolGauge.claimable_tokens(address(this)); return _pendingAltRewards( CRV, _user, stableCoinRewardsEarned, (totalSupply != 0) ? pendingCrv.mul(1e12).div(totalSupply) : 0 ); } function _pendingAltRewards(address token, address _user, uint256 userSupply, uint256 extraRewardsPerShare) internal view returns (uint256) { uint256 _altRewardsPerShare = altRewardsPerShare[token].add(extraRewardsPerShare); if (_altRewardsPerShare == 0) return 0; IStaking.AltRewardsUserInfo memory altRewardsUserInfo = userAltRewardsPerShare[_user][token]; return altRewardsUserInfo.pendingRewards.add( (_altRewardsPerShare.sub(altRewardsUserInfo.rewardsPerShare)).mul(userSupply).div(1e12) ); } function _depositToSushiMasterchef(uint256 amount) internal { uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this)); IMasterChefSushi(SUSHI_MASTERCHEF).deposit( BZRX_ETH_SUSHI_MASTERCHEF_PID, amount ); uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore; if (sushiRewards != 0) { _addAltRewards(SUSHI, sushiRewards); } } function _withdrawFromSushiMasterchef(uint256 amount) internal { uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this)); IMasterChefSushi(SUSHI_MASTERCHEF).withdraw( BZRX_ETH_SUSHI_MASTERCHEF_PID, amount ); uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore; if (sushiRewards != 0) { _addAltRewards(SUSHI, sushiRewards); } } function _depositTo3Pool( uint256 amount) internal { if(amount == 0) curve3PoolGauge.deposit(curve3Crv.balanceOf(address(this))); // Trigger claim rewards from curve pool uint256 crvBalanceBefore = IERC20(CRV).balanceOf(address(this)); curveMinter.mint(address(curve3PoolGauge)); uint256 crvBalanceAfter = IERC20(CRV).balanceOf(address(this)) - crvBalanceBefore; if(crvBalanceAfter != 0){ _addAltRewards(CRV, crvBalanceAfter); } } function _withdrawFrom3Pool(uint256 amount) internal { if(amount != 0) curve3PoolGauge.withdraw(amount); //Trigger claim rewards from curve pool uint256 crvBalanceBefore = IERC20(CRV).balanceOf(address(this)); curveMinter.mint(address(curve3PoolGauge)); uint256 crvBalanceAfter = IERC20(CRV).balanceOf(address(this)) - crvBalanceBefore; if(crvBalanceAfter != 0){ _addAltRewards(CRV, crvBalanceAfter); } } function stake( address[] memory tokens, uint256[] memory values ) public pausable updateRewards(msg.sender) { require(tokens.length == values.length, "count mismatch"); StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address currentDelegate = _voteDelegator.delegates(msg.sender); ProposalState memory _proposalState = _getProposalState(); uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken, "invalid token"); uint256 stakeAmount = values[i]; if (stakeAmount == 0) { continue; } uint256 pendingBefore = (token == LPToken) ? _pendingSushiRewards(msg.sender) : 0; _balancesPerToken[token][msg.sender] = _balancesPerToken[token][msg.sender].add(stakeAmount); _totalSupplyPerToken[token] = _totalSupplyPerToken[token].add(stakeAmount); IERC20(token).safeTransferFrom(msg.sender, address(this), stakeAmount); // Deposit to sushi masterchef if (token == LPToken) { _depositToSushiMasterchef( IERC20(LPToken).balanceOf(address(this)) ); userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[SUSHI], pendingRewards: pendingBefore } ); } emit Stake( msg.sender, token, currentDelegate, stakeAmount ); } _voteDelegator.moveDelegates(ZERO_ADDRESS, currentDelegate, _votingFromStakedBalanceOf(msg.sender, _proposalState, true).sub(votingBalanceBefore)); } function unstake( address[] memory tokens, uint256[] memory values ) public pausable updateRewards(msg.sender) { require(tokens.length == values.length, "count mismatch"); StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address currentDelegate = _voteDelegator.delegates(msg.sender); ProposalState memory _proposalState = _getProposalState(); uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken || token == LPTokenOld, "invalid token"); uint256 unstakeAmount = values[i]; uint256 stakedAmount = _balancesPerToken[token][msg.sender]; if (unstakeAmount == 0 || stakedAmount == 0) { continue; } if (unstakeAmount > stakedAmount) { unstakeAmount = stakedAmount; } uint256 pendingBefore = (token == LPToken) ? _pendingSushiRewards(msg.sender) : 0; _balancesPerToken[token][msg.sender] = stakedAmount - unstakeAmount; // will not overflow _totalSupplyPerToken[token] = _totalSupplyPerToken[token] - unstakeAmount; // will not overflow if (token == BZRX && IERC20(BZRX).balanceOf(address(this)) < unstakeAmount) { // settle vested BZRX only if needed IVestingToken(vBZRX).claim(); } // Withdraw to sushi masterchef if (token == LPToken) { _withdrawFromSushiMasterchef(unstakeAmount); userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[SUSHI], pendingRewards: pendingBefore } ); } IERC20(token).safeTransfer(msg.sender, unstakeAmount); emit Unstake( msg.sender, token, currentDelegate, unstakeAmount ); } _voteDelegator.moveDelegates(currentDelegate, ZERO_ADDRESS, votingBalanceBefore.sub(_votingFromStakedBalanceOf(msg.sender, _proposalState, true))); } function claim( bool restake) external pausable updateRewards(msg.sender) returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned) { return _claim(restake); } function claimAltRewards() external pausable returns (uint256 sushiRewardsEarned, uint256 crvRewardsEarned) { sushiRewardsEarned = _claimSushi(); crvRewardsEarned = _claimCrv(); if(sushiRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned); } if(crvRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, CRV, crvRewardsEarned); } } function claimBzrx() external pausable updateRewards(msg.sender) returns (uint256 bzrxRewardsEarned) { bzrxRewardsEarned = _claimBzrx(false); emit Claim( msg.sender, bzrxRewardsEarned, 0 ); } function claim3Crv() external pausable updateRewards(msg.sender) returns (uint256 stableCoinRewardsEarned) { stableCoinRewardsEarned = _claim3Crv(); emit Claim( msg.sender, 0, stableCoinRewardsEarned ); } function claimSushi() external pausable returns (uint256 sushiRewardsEarned) { sushiRewardsEarned = _claimSushi(); if(sushiRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned); } } function claimCrv() external pausable returns (uint256 crvRewardsEarned) { crvRewardsEarned = _claimCrv(); if(crvRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, CRV, crvRewardsEarned); } } function _claim( bool restake) internal returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned) { bzrxRewardsEarned = _claimBzrx(restake); stableCoinRewardsEarned = _claim3Crv(); emit Claim( msg.sender, bzrxRewardsEarned, stableCoinRewardsEarned ); } function _claimBzrx( bool restake) internal returns (uint256 bzrxRewardsEarned) { bzrxRewardsEarned = bzrxRewards[msg.sender]; if (bzrxRewardsEarned != 0) { bzrxRewards[msg.sender] = 0; if (restake) { _restakeBZRX( msg.sender, bzrxRewardsEarned ); } else { if (IERC20(BZRX).balanceOf(address(this)) < bzrxRewardsEarned) { // settle vested BZRX only if needed IVestingToken(vBZRX).claim(); } IERC20(BZRX).transfer(msg.sender, bzrxRewardsEarned); } } } function _claim3Crv() internal returns (uint256 stableCoinRewardsEarned) { stableCoinRewardsEarned = stableCoinRewards[msg.sender]; if (stableCoinRewardsEarned != 0) { uint256 pendingCrv = _pendingCrvRewards(msg.sender, stableCoinRewardsEarned); uint256 curve3CrvBalance = curve3Crv.balanceOf(address(this)); _withdrawFrom3Pool(stableCoinRewardsEarned); userAltRewardsPerShare[msg.sender][CRV] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[CRV], pendingRewards: pendingCrv } ); stableCoinRewards[msg.sender] = 0; curve3Crv.transfer(msg.sender, stableCoinRewardsEarned); } } function _claimSushi() internal returns (uint256) { address _user = msg.sender; uint256 lptUserSupply = balanceOfByAsset(LPToken, _user); //This will trigger claim rewards from sushi masterchef _depositToSushiMasterchef( IERC20(LPToken).balanceOf(address(this)) ); uint256 pendingSushi = _pendingAltRewards(SUSHI, _user, lptUserSupply, 0); userAltRewardsPerShare[_user][SUSHI] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[SUSHI], pendingRewards: 0 } ); if (pendingSushi != 0) { IERC20(SUSHI).safeTransfer(_user, pendingSushi); } return pendingSushi; } function _claimCrv() internal returns (uint256) { address _user = msg.sender; _depositTo3Pool(0); (,uint256 stableCoinRewardsEarned,,) = _earned(_user, bzrxPerTokenStored, stableCoinPerTokenStored); uint256 pendingCrv = _pendingCrvRewards(_user, stableCoinRewardsEarned); userAltRewardsPerShare[_user][CRV] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[CRV], pendingRewards: 0 } ); if (pendingCrv != 0) { IERC20(CRV).safeTransfer(_user, pendingCrv); } return pendingCrv; } function _restakeBZRX( address account, uint256 amount) internal { StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address currentDelegate = _voteDelegator.delegates(msg.sender); ProposalState memory _proposalState = _getProposalState(); uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true); _balancesPerToken[BZRX][account] = _balancesPerToken[BZRX][account] .add(amount); _totalSupplyPerToken[BZRX] = _totalSupplyPerToken[BZRX] .add(amount); emit Stake( account, BZRX, currentDelegate, amount ); _voteDelegator.moveDelegates(ZERO_ADDRESS, currentDelegate, _votingFromStakedBalanceOf(msg.sender, _proposalState, true).sub(votingBalanceBefore)); } function exit() public // unstake() does check pausable { address[] memory tokens = new address[](4); uint256[] memory values = new uint256[](4); tokens[0] = iBZRX; tokens[1] = LPToken; tokens[2] = vBZRX; tokens[3] = BZRX; values[0] = uint256(-1); values[1] = uint256(-1); values[2] = uint256(-1); values[3] = uint256(-1); unstake(tokens, values); // calls updateRewards _claim(false); } modifier updateRewards(address account) { uint256 _bzrxPerTokenStored = bzrxPerTokenStored; uint256 _stableCoinPerTokenStored = stableCoinPerTokenStored; (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned( account, _bzrxPerTokenStored, _stableCoinPerTokenStored ); bzrxRewardsPerTokenPaid[account] = _bzrxPerTokenStored; stableCoinRewardsPerTokenPaid[account] = _stableCoinPerTokenStored; // vesting amounts get updated before sync bzrxVesting[account] = bzrxRewardsVesting; stableCoinVesting[account] = stableCoinRewardsVesting; (bzrxRewards[account], stableCoinRewards[account]) = _syncVesting( account, bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting ); vestingLastSync[account] = block.timestamp; _; } function earned( address account) external view returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned) { (bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting) = _earned( account, bzrxPerTokenStored, stableCoinPerTokenStored ); (bzrxRewardsEarned, stableCoinRewardsEarned) = _syncVesting( account, bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting ); // discount vesting amounts for vesting time uint256 multiplier = vestedBalanceForAmount( 1e36, 0, block.timestamp ); bzrxRewardsVesting = bzrxRewardsVesting .sub(bzrxRewardsVesting .mul(multiplier) .div(1e36) ); stableCoinRewardsVesting = stableCoinRewardsVesting .sub(stableCoinRewardsVesting .mul(multiplier) .div(1e36) ); uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF) .pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this)); sushiRewardsEarned = _pendingAltRewards( SUSHI, account, balanceOfByAsset(LPToken, account), (_totalSupplyPerToken[LPToken] != 0) ? pendingSushi.mul(1e12).div(_totalSupplyPerToken[LPToken]) : 0 ); } function _earned( address account, uint256 _bzrxPerToken, uint256 _stableCoinPerToken) internal view returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) { uint256 bzrxPerTokenUnpaid = _bzrxPerToken.sub(bzrxRewardsPerTokenPaid[account]); uint256 stableCoinPerTokenUnpaid = _stableCoinPerToken.sub(stableCoinRewardsPerTokenPaid[account]); bzrxRewardsEarned = bzrxRewards[account]; stableCoinRewardsEarned = stableCoinRewards[account]; bzrxRewardsVesting = bzrxVesting[account]; stableCoinRewardsVesting = stableCoinVesting[account]; if (bzrxPerTokenUnpaid != 0 || stableCoinPerTokenUnpaid != 0) { uint256 value; uint256 multiplier; uint256 lastSync; (uint256 vestedBalance, uint256 vestingBalance) = balanceOfStored(account); value = vestedBalance .mul(bzrxPerTokenUnpaid); value /= 1e36; bzrxRewardsEarned = value .add(bzrxRewardsEarned); value = vestedBalance .mul(stableCoinPerTokenUnpaid); value /= 1e36; stableCoinRewardsEarned = value .add(stableCoinRewardsEarned); if (vestingBalance != 0 && bzrxPerTokenUnpaid != 0) { // add new vesting amount for BZRX value = vestingBalance .mul(bzrxPerTokenUnpaid); value /= 1e36; bzrxRewardsVesting = bzrxRewardsVesting .add(value); // true up earned amount to vBZRX vesting schedule lastSync = vestingLastSync[account]; multiplier = vestedBalanceForAmount( 1e36, 0, lastSync ); value = value .mul(multiplier); value /= 1e36; bzrxRewardsEarned = bzrxRewardsEarned .add(value); } if (vestingBalance != 0 && stableCoinPerTokenUnpaid != 0) { // add new vesting amount for 3crv value = vestingBalance .mul(stableCoinPerTokenUnpaid); value /= 1e36; stableCoinRewardsVesting = stableCoinRewardsVesting .add(value); // true up earned amount to vBZRX vesting schedule if (lastSync == 0) { lastSync = vestingLastSync[account]; multiplier = vestedBalanceForAmount( 1e36, 0, lastSync ); } value = value .mul(multiplier); value /= 1e36; stableCoinRewardsEarned = stableCoinRewardsEarned .add(value); } } } function _syncVesting( address account, uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) internal view returns (uint256, uint256) { uint256 lastVestingSync = vestingLastSync[account]; if (lastVestingSync != block.timestamp) { uint256 rewardsVested; uint256 multiplier = vestedBalanceForAmount( 1e36, lastVestingSync, block.timestamp ); if (bzrxRewardsVesting != 0) { rewardsVested = bzrxRewardsVesting .mul(multiplier) .div(1e36); bzrxRewardsEarned += rewardsVested; } if (stableCoinRewardsVesting != 0) { rewardsVested = stableCoinRewardsVesting .mul(multiplier) .div(1e36); stableCoinRewardsEarned += rewardsVested; } uint256 vBZRXBalance = _balancesPerToken[vBZRX][account]; if (vBZRXBalance != 0) { // add vested BZRX to rewards balance rewardsVested = vBZRXBalance .mul(multiplier) .div(1e36); bzrxRewardsEarned += rewardsVested; } } return (bzrxRewardsEarned, stableCoinRewardsEarned); } // note: anyone can contribute rewards to the contract function addDirectRewards( address[] calldata accounts, uint256[] calldata bzrxAmounts, uint256[] calldata stableCoinAmounts) external pausable returns (uint256 bzrxTotal, uint256 stableCoinTotal) { require(accounts.length == bzrxAmounts.length && accounts.length == stableCoinAmounts.length, "count mismatch"); for (uint256 i = 0; i < accounts.length; i++) { bzrxRewards[accounts[i]] = bzrxRewards[accounts[i]].add(bzrxAmounts[i]); bzrxTotal = bzrxTotal.add(bzrxAmounts[i]); stableCoinRewards[accounts[i]] = stableCoinRewards[accounts[i]].add(stableCoinAmounts[i]); stableCoinTotal = stableCoinTotal.add(stableCoinAmounts[i]); } if (bzrxTotal != 0) { IERC20(BZRX).transferFrom(msg.sender, address(this), bzrxTotal); } if (stableCoinTotal != 0) { curve3Crv.transferFrom(msg.sender, address(this), stableCoinTotal); _depositTo3Pool(stableCoinTotal); } } // note: anyone can contribute rewards to the contract function addRewards( uint256 newBZRX, uint256 newStableCoin) external pausable { if (newBZRX != 0 || newStableCoin != 0) { _addRewards(newBZRX, newStableCoin); if (newBZRX != 0) { IERC20(BZRX).transferFrom(msg.sender, address(this), newBZRX); } if (newStableCoin != 0) { curve3Crv.transferFrom(msg.sender, address(this), newStableCoin); _depositTo3Pool(newStableCoin); } } } function _addRewards( uint256 newBZRX, uint256 newStableCoin) internal { (vBZRXWeightStored, iBZRXWeightStored, LPTokenWeightStored) = getVariableWeights(); uint256 totalTokens = totalSupplyStored(); require(totalTokens != 0, "nothing staked"); bzrxPerTokenStored = newBZRX .mul(1e36) .div(totalTokens) .add(bzrxPerTokenStored); stableCoinPerTokenStored = newStableCoin .mul(1e36) .div(totalTokens) .add(stableCoinPerTokenStored); lastRewardsAddTime = block.timestamp; emit AddRewards( msg.sender, newBZRX, newStableCoin ); } function addAltRewards(address token, uint256 amount) public { if (amount != 0) { _addAltRewards(token, amount); IERC20(token).transferFrom(msg.sender, address(this), amount); } } function _addAltRewards(address token, uint256 amount) internal { address poolAddress = token == SUSHI ? LPToken : token; uint256 totalSupply = (token == CRV) ? curve3PoolGauge.balanceOf(address(this)) :_totalSupplyPerToken[poolAddress]; require(totalSupply != 0, "no deposits"); altRewardsPerShare[token] = altRewardsPerShare[token] .add(amount.mul(1e12).div(totalSupply)); emit AddAltRewards(msg.sender, token, amount); } function getVariableWeights() public view returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight) { uint256 totalVested = vestedBalanceForAmount( _startingVBZRXBalance, 0, block.timestamp ); vBZRXWeight = SafeMath.mul(_startingVBZRXBalance - totalVested, 1e18) // overflow not possible .div(_startingVBZRXBalance); iBZRXWeight = _calcIBZRXWeight(); uint256 lpTokenSupply = _totalSupplyPerToken[LPToken]; if (lpTokenSupply != 0) { // staked LP tokens are assumed to represent the total unstaked supply (circulated supply - staked BZRX) uint256 normalizedLPTokenSupply = initialCirculatingSupply + totalVested - _totalSupplyPerToken[BZRX]; LPTokenWeight = normalizedLPTokenSupply .mul(1e18) .div(lpTokenSupply); } } function _calcIBZRXWeight() internal view returns (uint256) { return IERC20(BZRX).balanceOf(iBZRX) .mul(1e50) .div(IERC20(iBZRX).totalSupply()); } function balanceOfByAsset( address token, address account) public view returns (uint256 balance) { balance = _balancesPerToken[token][account]; } function balanceOfByAssets( address account) external view returns ( uint256 bzrxBalance, uint256 iBZRXBalance, uint256 vBZRXBalance, uint256 LPTokenBalance, uint256 LPTokenBalanceOld ) { return ( balanceOfByAsset(BZRX, account), balanceOfByAsset(iBZRX, account), balanceOfByAsset(vBZRX, account), balanceOfByAsset(LPToken, account), balanceOfByAsset(LPTokenOld, account) ); } function balanceOfStored( address account) public view returns (uint256 vestedBalance, uint256 vestingBalance) { uint256 balance = _balancesPerToken[vBZRX][account]; if (balance != 0) { vestingBalance = balance .mul(vBZRXWeightStored) .div(1e18); } vestedBalance = _balancesPerToken[BZRX][account]; balance = _balancesPerToken[iBZRX][account]; if (balance != 0) { vestedBalance = balance .mul(iBZRXWeightStored) .div(1e50) .add(vestedBalance); } balance = _balancesPerToken[LPToken][account]; if (balance != 0) { vestedBalance = balance .mul(LPTokenWeightStored) .div(1e18) .add(vestedBalance); } } function totalSupplyByAsset( address token) external view returns (uint256) { return _totalSupplyPerToken[token]; } function totalSupplyStored() public view returns (uint256 supply) { supply = _totalSupplyPerToken[vBZRX] .mul(vBZRXWeightStored) .div(1e18); supply = _totalSupplyPerToken[BZRX] .add(supply); supply = _totalSupplyPerToken[iBZRX] .mul(iBZRXWeightStored) .div(1e50) .add(supply); supply = _totalSupplyPerToken[LPToken] .mul(LPTokenWeightStored) .div(1e18) .add(supply); } function vestedBalanceForAmount( uint256 tokenBalance, uint256 lastUpdate, uint256 vestingEndTime) public view returns (uint256 vested) { vestingEndTime = vestingEndTime.min256(block.timestamp); if (vestingEndTime > lastUpdate) { if (vestingEndTime <= vestingCliffTimestamp || lastUpdate >= vestingEndTimestamp) { // time cannot be before vesting starts // OR all vested token has already been claimed return 0; } if (lastUpdate < vestingCliffTimestamp) { // vesting starts at the cliff timestamp lastUpdate = vestingCliffTimestamp; } if (vestingEndTime > vestingEndTimestamp) { // vesting ends at the end timestamp vestingEndTime = vestingEndTimestamp; } uint256 timeSinceClaim = vestingEndTime.sub(lastUpdate); vested = tokenBalance.mul(timeSinceClaim) / vestingDurationAfterCliff; // will never divide by 0 } } function votingFromStakedBalanceOf( address account) external view returns (uint256 totalVotes) { return _votingFromStakedBalanceOf(account, _getProposalState(), true); } function votingBalanceOf( address account, uint256 proposalId) external view returns (uint256 totalVotes) { (,,,uint256 startBlock,,,,,,) = GovernorBravoDelegateStorageV1(governor).proposals(proposalId); if (startBlock == 0) return 0; return _votingBalanceOf(account, _proposalState[proposalId], startBlock - 1); } function votingBalanceOfNow( address account) external view returns (uint256 totalVotes) { return _votingBalanceOf(account, _getProposalState(), block.number - 1); } function _setProposalVals( address account, uint256 proposalId) public returns (uint256) { require(msg.sender == governor, "unauthorized"); require(_proposalState[proposalId].proposalTime == 0, "proposal exists"); ProposalState memory newProposal = _getProposalState(); _proposalState[proposalId] = newProposal; return _votingBalanceOf(account, newProposal, block.number - 1); } function _getProposalState() internal view returns (ProposalState memory) { return ProposalState({ proposalTime: block.timestamp - 1, iBZRXWeight: _calcIBZRXWeight(), lpBZRXBalance: 0, // IERC20(BZRX).balanceOf(LPToken), lpTotalSupply: 0 //IERC20(LPToken).totalSupply() }); } // Voting balance not including delegated votes function _votingFromStakedBalanceOf( address account, ProposalState memory proposal, bool skipVestingLastSyncCheck) internal view returns (uint256 totalVotes) { uint256 _vestingLastSync = vestingLastSync[account]; if (proposal.proposalTime == 0 || (!skipVestingLastSyncCheck && _vestingLastSync > proposal.proposalTime - 1)) { return 0; } // user is attributed a staked balance of vested BZRX, from their last update to the present totalVotes = vestedBalanceForAmount( _balancesPerToken[vBZRX][account], _vestingLastSync, proposal.proposalTime ); totalVotes = _balancesPerToken[BZRX][account] .add(bzrxRewards[account]) // unclaimed BZRX rewards count as votes .add(totalVotes); totalVotes = _balancesPerToken[iBZRX][account] .mul(proposal.iBZRXWeight) .div(1e50) .add(totalVotes); } // Voting balance including delegated votes function _votingBalanceOf( address account, ProposalState memory proposal, uint blocknumber) internal view returns (uint256 totalVotes) { StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address _delegate = _voteDelegator.delegates(account); if(_delegate == ZERO_ADDRESS) { // has not delegated yet return _voteDelegator.getPriorVotes(account, blocknumber).add(_votingFromStakedBalanceOf(account, proposal, false)); } return _voteDelegator.getPriorVotes(account, blocknumber); } // OnlyOwner functions function updateSettings( address settingsTarget, bytes memory callData) public onlyOwner returns(bytes memory) { (bool result,) = settingsTarget.delegatecall(callData); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) if eq(result, 0) { revert(ptr, size) } return(ptr, size) } } }
Allows batching to castVote function/
function castVotes(uint[] calldata proposalIds, uint8[] calldata supportVals) external { require(proposalIds.length == supportVals.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), ""); } }
260,306
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "./MultiModelNftUpgradeableBase.sol"; import "../../lib/access/OwnableUpgradeable.sol"; import "../../lib/opensea/OpenseaERC721Upgradeable.sol"; contract MultiModelNftUpgradeableSub is MultiModelNftUpgradeableBase { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; // Events event AddModel (uint8 class, string name, string metafileUri, uint256 capacity, uint256 mintPrice, bytes4[] defaultColor, uint8 bonus); event ModelNewUri (uint256 indexed modelId, string newUri); event ModelNewMintPrice (uint256 indexed modelId, uint256 newMintPrice); event ModelNewCapacity (uint256 indexed modelId, uint256 newCapacity); event ModelNewAirdropCapacity (uint256 indexed modelId, uint256 newCapacity); event Airdrop (uint256 indexed modelId, address indexed account, uint256 airdropNonce, uint256 indexed tokenId); /** * @notice Add a new model. * @param _classes Class of the model * @param _names Name of the model * @param _metafileUris URI of the model * @param _capacities Capacity of the model * @param _mintPrices Minting price in ETH * @param _defaultColors Default color of the model * @param _bonuses Bonus of the model */ function addModels( uint8[] memory _classes, string[] memory _names, string[] memory _metafileUris, uint256[] memory _capacities, uint256[] memory _mintPrices, bytes4[][] memory _defaultColors, uint8[] memory _bonuses ) external onlyOwner() { require( _classes.length == _names.length && _classes.length == _metafileUris.length && _classes.length == _capacities.length && _classes.length == _mintPrices.length && _classes.length == _defaultColors.length && _classes.length == _bonuses.length, "Mismatched data" ); for (uint256 i = 0; i < _bonuses.length; i ++) { Model memory model = Model({ bonus: _bonuses[i], class: _classes[i], name: _names[i], metafileUri: _metafileUris[i], capacity: _capacities[i], supply: 0, mintPrice: _mintPrices[i], defaultColor: _defaultColors[i], airdropCapacity: _capacities[i], airdropSupply: 0 }); models.push(model); emit AddModel (model.class, model.name, model.metafileUri, model.capacity, model.mintPrice, model.defaultColor, model.bonus); } } function setModelUri(uint256 _modelId, string memory _metafileUri) external onlyOwner() { require(_modelId < modelCount(), "Invalid model ID"); models[_modelId].metafileUri = _metafileUri; emit ModelNewUri(_modelId, models[_modelId].metafileUri); } function setModelMintPrice(uint256 _modelId, uint256 _mintPrice) external onlyOwner() { require(_modelId < modelCount(), "Invalid model ID"); models[_modelId].mintPrice = _mintPrice; emit ModelNewMintPrice(_modelId, models[_modelId].mintPrice); } function setModelCapacities(uint256[] memory _modelIds, uint256[] memory _capacities) external onlyOwner() { require(_modelIds.length == _capacities.length, "Mismatched data"); for (uint256 i = 0; i < _modelIds.length; i ++) { uint256 _modelId = _modelIds[i]; uint256 _capacity = _capacities[i]; require(_modelId < modelCount(), "Invalid model ID"); require(models[_modelId].supply <= _capacity, "New capacity should be equal or greater than the current supply"); models[_modelId].capacity = _capacity; emit ModelNewCapacity(_modelId, models[_modelId].capacity); } } function setModelAirdropCapacities(uint256[] memory _modelIds, uint256[] memory _capacities) external onlyOwner() { require(_modelIds.length == _capacities.length, "Mismatched data"); for (uint256 i = 0; i < _modelIds.length; i ++) { uint256 _modelId = _modelIds[i]; uint256 _capacity = _capacities[i]; require(_modelId < modelCount(), "Invalid model ID"); require(models[_modelId].airdropSupply <= _capacity, "New capacity should be equal or greater than the current supply"); models[_modelId].airdropCapacity = _capacity; emit ModelNewAirdropCapacity(_modelId, models[_modelId].airdropCapacity); } } /** * @dev Airdrop tokens to the specifeid addresses (Callable by owner). * The supply is limited as 30 to avoid spending much gas and to avoid exceed block gas limit. */ function doAirdrop(uint256 _modelId, address[] memory _accounts) external returns(uint256 leftCapacity) { require(hasRole(ALLOWED_MINTERS, _msgSender()), "MultiModelNft: Restricted access to minters"); require(_modelId < modelCount(), "MultiModelNft: Invalid model ID"); require(0 < _accounts.length, "MultiModelNft: No account address"); require(_accounts.length <= 30, "MultiModelNft: Exceeds limit"); Model storage model = models[_modelId]; require((model.airdropSupply + _accounts.length) <= model.airdropCapacity, "MultiModelNft: Exceeds capacity"); model.airdropSupply += _accounts.length; for (uint i = 0; i < _accounts.length; i ++) { address account = _accounts[i]; uint256 tokenId = ++ _currentTokenId; modelIds[tokenId] = _modelId; _safeMint(account, tokenId); emit Airdrop(_modelId, account, type(uint256).max, tokenId); } leftCapacity = model.airdropCapacity.sub(model.airdropSupply); } function doAirdropBySignature(uint256 _modelId, address _account, uint256 _quantity, bytes memory _signature) external returns(uint256 leftCapacity) { require(_modelId < modelCount(), "MultiModelNft: Invalid model ID"); require(_isValidSignature(_modelId, _account, _quantity, _signature), "MultiModelNft: Invalid signature"); Model storage model = models[_modelId]; require((model.airdropSupply + _quantity) <= model.airdropCapacity, "MultiModelNft: Exceeds capacity"); model.airdropSupply += _quantity; for (uint i = 0; i < _quantity; i ++) { uint256 tokenId = ++ _currentTokenId; uint256 airdropNonce = airdropNonces[_account]; modelIds[tokenId] = _modelId; airdropNonces[_account] ++; _safeMint(_account, tokenId); emit Airdrop(_modelId, _account, airdropNonce, tokenId); } leftCapacity = model.airdropCapacity.sub(model.airdropSupply); } function _isValidSignature(uint256 _modelId, address _account, uint256 _quantity, bytes memory _signature) internal view returns (bool) { bytes32 message = keccak256(abi.encodePacked(address(this), _modelId, _account, _quantity, airdropNonces[_account])); bytes32 messageHash = ECDSAUpgradeable.toEthSignedMessageHash(message); // check that the signature is from admin signer. address recoveredAddress = ECDSAUpgradeable.recover(messageHash, _signature); return hasRole(ALLOWED_MINTERS, recoveredAddress); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../../lib/access/OwnableUpgradeable.sol"; import "../../lib/opensea/OpenseaERC721Upgradeable.sol"; import "../../PriceOracle/IPriceOracleUpgradeable.sol"; import "../../NYM/INymLib.sol"; contract MultiModelNftUpgradeableBase is OwnableUpgradeable, OpenseaERC721Upgradeable, AccessControlUpgradeable { struct Model { // Bonus percent of the model uint8 bonus; // Class of the model uint8 class; // Name of the model string name; // URI of the model string metafileUri; // Capacity mintable by user uint256 capacity; // Count of token of the model uint256 supply; // Minting price in ETH uint256 mintPrice; // Default color of the model bytes4[] defaultColor; // Capacity of airdrop uint256 airdropCapacity; // Count of token airdropped uint256 airdropSupply; } INymLib public nymLib; IPriceOracleUpgradeable public priceOracle; uint256 internal _currentTokenId = 0; /// @notice The address of the GridZone token IERC20Upgradeable public zoneToken; // Mapping from token ID to name mapping (uint256 => string) internal _tokenName; // Mapping if certain name string has already been reserved mapping (string => bool) internal _nameReserved; // Option to changeable name bool public nameChangeable; // Option to changeable color bool public colorChangeable; // Mapping if certain name string has already been reserved mapping (uint256 => bytes4[]) internal _colors; // Array of models Model[] public models; // Mapping from token ID to model ID mapping (uint256 => uint256) public modelIds; // The nonce for airdrop. mapping(address => uint256) public airdropNonces; // Address of sub-implementation contract address public subImpl; bytes32 public constant ALLOWED_MINTERS = keccak256("ALLOWED_MINTERS"); function _msgSender() internal override view returns (address payable) { return EIP712MetaTxUpgradeable.msgSender(); } function modelCount() public view returns (uint256) { return models.length; } uint256[38] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init(address _ownerAddress) internal initializer { __Context_init_unchained(); __Ownable_init_unchained(_ownerAddress); } function __Ownable_init_unchained(address _ownerAddress) internal initializer { _owner = _ownerAddress; emit OwnershipTransferred(address(0), _ownerAddress); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view virtual returns (address) { return _pendingOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function safeTransferOwnership(address newOwner, bool safely) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); if (safely) { _pendingOwner = newOwner; } else { emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; _pendingOwner = address(0); } } function safeAcceptOwnership() public virtual { require(_msgSender() == _pendingOwner, "acceptOwnership: Call must come from pendingOwner."); emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; } uint256[48] private __gap; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "../eip712/EIP712MetaTxUpgradeable.sol"; import "./OpenseaProxyRegistry.sol"; /** * @title OpenseaERC721Upgradeable * @dev ERC721 contract that whitelists a trading address, and has minting functionality. * Refer to https://github.com/ProjectOpenSea/opensea-creatures/blob/master/contracts/ERC721Tradable.sol */ contract OpenseaERC721Upgradeable is ERC721Upgradeable, EIP712MetaTxUpgradeable { address public proxyRegistryAddress; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __OpenseaERC721_init_unchained( string memory _name, string memory _symbol, address _proxyRegistryAddress ) internal initializer { __ERC721_init(_name, _symbol); __EIP712MetaTx_init_unchained(_name, "1"); proxyRegistryAddress = _proxyRegistryAddress; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address tokenOwner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. if (proxyRegistryAddress != address(0)) { OpenseaProxyRegistry proxyRegistry = OpenseaProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(tokenOwner)) == operator) { return true; } } return super.isApprovedForAll(tokenOwner, operator); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../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: GPL-3.0-or-later pragma solidity 0.7.6; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; interface IPriceOracleUpgradeable { function zoneToken() external view returns(address); function lpZoneEth() external view returns(IUniswapV2Pair); function getOutAmount(address token, uint256 tokenAmount) external view returns (uint256); function mintPriceInZone(uint256 _mintPrice) external returns (uint256); function getLPFairPrice() external view returns (uint256); } // SPDX-License-Identifier:MIT pragma solidity 0.7.6; interface INymLib { function toBase58(bytes memory source) external pure returns (string memory); function validateName(string memory str) external pure returns (bool); function toLower(string memory str) external pure returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721Upgradeable.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } uint256[41] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./EIP712BaseUpgradeable.sol"; contract EIP712MetaTxUpgradeable is EIP712BaseUpgradeable { using SafeMathUpgradeable for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(bytes("MetaTransaction(uint256 nonce,address from,bytes functionSignature)")); mapping(address => uint256) internal _nonces; event MetaTransactionExecuted(address indexed userAddress, address indexed relayerAddress, bytes functionSignature); /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function __EIP712MetaTx_init_unchained(string memory name, string memory version) internal initializer { __EIP712Base_init_unchained(name, version); } function convertBytesToBytes4(bytes memory inBytes) pure internal returns (bytes4 outBytes4) { if (inBytes.length == 0) { return 0x0; } assembly { outBytes4 := mload(add(inBytes, 32)) } } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns(bytes memory) { bytes4 destinationFunctionSig = convertBytesToBytes4(functionSignature); require(destinationFunctionSig != msg.sig, "EIP712MetaTx: functionSignature can not be of executeMetaTransaction method"); MetaTransaction memory metaTx = MetaTransaction({ nonce: _nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require(verify(userAddress, metaTx, sigR, sigS, sigV), "EIP712MetaTx: Signer and signature do not match"); _nonces[userAddress] = _nonces[userAddress].add(1); emit MetaTransactionExecuted(userAddress, msg.sender, functionSignature); // Append userAddress at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call(abi.encodePacked(functionSignature, userAddress)); require(success, "EIP712MetaTx: Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256(abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) )); } function getNonce(address user) external view returns(uint256) { return _nonces[user]; } function verify(address user, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV) internal view returns (bool) { address signer = ecrecover(toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS); require(signer != address(0), "EIP712MetaTx: Invalid signature"); return signer == user; } function msgSender() internal view returns(address payable sender) { if(msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } } else { sender = msg.sender; } return sender; } uint256[49] private __gap; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; contract OpenseaOwnableDelegateProxy {} contract OpenseaProxyRegistry { mapping(address => OpenseaOwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; contract EIP712BaseUpgradeable is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"); bytes32 internal domainSeparator; function __EIP712Base_init_unchained(string memory name, string memory version) internal initializer { domainSeparator = keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(version)), address(this), bytes32(getChainId()) )); } function getChainId() public pure returns (uint256 id) { assembly { id := chainid() } } function getDomainSeparator() public view returns(bytes32) { return domainSeparator; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns(bytes32) { return keccak256(abi.encodePacked("\x19\x01", getDomainSeparator(), messageHash)); } uint256[49] private __gap; } 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; }
Append userAddress at the end to extract it from calling context
emit MetaTransactionExecuted(userAddress, msg.sender, functionSignature); (bool success, bytes memory returnData) = address(this).call(abi.encodePacked(functionSignature, userAddress)); require(success, "EIP712MetaTx: Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256(abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) )); }
14,572,113
./full_match/1/0x3d9246C38c9e8A22D1f4d2742e28CEd721897647/sources/contracts/aludel/Aludel.sol
Rescue tokens from RewardPool use this function to rescue tokens from RewardPool contract without distributing to stakers or triggering emergency shutdown access control: only admin state machine: - can be called multiple times - only online state scope: none token transfer: transfer requested token from RewardPool to recipient token address The address of the token to rescue recipient address The address of the recipient amount uint256 The amount of tokens to rescue verify recipient check not attempting to unstake reward token check not attempting to wthdraw bonus token transfer tokens to recipient
function rescueTokensFromRewardPool( address token, address recipient, uint256 amount ) external override onlyOwner onlyOnline { _validateAddress(recipient); require(token != _aludel.rewardToken, "Aludel: invalid address"); require(!_bonusTokenSet.contains(token), "Aludel: invalid address"); IRewardPool(_aludel.rewardPool).sendERC20(token, recipient, amount); }
9,822,091
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './libraries/Math.sol'; import './interfaces/ISfpyPool.sol'; import './interfaces/ISfpyERC20.sol'; import './interfaces/ISfpyFactory.sol'; import './interfaces/ISfpyBorrower.sol'; import './SfpyERC20.sol'; contract SfpyPool is SfpyERC20 { using SafeMath for uint256; uint256 private constant ETHER = 1 ether; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address private _factory; address private _token; uint112 private reserve; uint32 private blockTimestampLast; uint256 private unlocked = 1; modifier lock() { require(unlocked == 1, 'SFPY: LOCKED'); unlocked = 0; _; unlocked = 1; } /// @dev Get the pool's balance of token function getReserves() public view returns (uint112 _reserve, uint32 _blockTimestampLast) { _reserve = reserve; _blockTimestampLast = blockTimestampLast; } function _safeTransfer( address to, uint256 value ) private { (bool success, bytes memory data) = _token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SFPY: TRANSFER_FAILED'); } event Mint(address indexed sender, uint256 amount); event Burn(address indexed sender, uint256 amount, address indexed to); event Sync(uint112 reserve); constructor() { _factory = msg.sender; } function initialize(address t) external { require(msg.sender == _factory, 'SFPY: FORBIDDEN'); _token = t; } /// @dev updates the reserve value of the pool after every /// @dev interaction that changes state such as mint, burn /// @dev and borrow /// @param balance the updated reserve value of the pool function _update(uint256 balance) private { require(balance <= 2**112 - 1, 'SFPY: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); reserve = uint112(balance); blockTimestampLast = blockTimestamp; emit Sync(reserve); } /// @dev calculates the amount of liquidity tokens needed to be burnt /// @dev given an amount of the underlying token /// @param amount the amount of ERC-20 tokens that is needed function liquidityToBurn(uint256 amount) public view returns (uint256 liquidity) { uint256 _ts = totalSupply(); uint256 balance = ISfpyERC20(_token).balanceOf(address(this)); require(balance > 0, 'SFPY: INSUFFICIENT_BALANCE'); liquidity = amount.mul(_ts) / balance; require(liquidity > 0, 'SFPY: INSUFFICIENT_LIQUIDITY'); } /// @dev mints liquidity tokens pro rata based on the amount of the /// @dev underlying ERC-20 token that was transferred to the pool /// @param to the address to mint the liquidity tokens to function mint(address to) external lock returns (uint256 liquidity) { (uint112 _reserve, ) = getReserves(); // gas savings uint256 balance = ISfpyERC20(_token).balanceOf(address(this)); uint256 amount = balance.sub(_reserve); uint256 _ts = totalSupply(); if (_ts == 0) { liquidity = Math.sqrt(amount.mul(ETHER)); } else { liquidity = amount.mul(ETHER) / _ts; } require(liquidity > 0, 'SFPY: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance); emit Mint(msg.sender, amount); } /// @dev converts pool liquidity tokens into underlying ERC-20 tokens /// @dev and sends them to the address specified /// @param to the address to send the underlying tokens to function burn(address to) external lock returns (uint256 amount) { uint256 balance = ISfpyERC20(_token).balanceOf(address(this)); uint256 liquidity = balanceOf(address(this)); uint256 _ts = totalSupply(); amount = liquidity.mul(balance) / _ts; require(amount > 0, 'SFPY: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(to, amount); balance = ISfpyERC20(_token).balanceOf(address(this)); _update(balance); emit Burn(msg.sender, amount, to); } /// @dev Borrows funds from the pool /// @param amountOut the amount requested /// @param to the address to send the funds to /// @param data any data that might be needed during call execution function borrow(uint amountOut, address to, bytes calldata data) external lock { require(amountOut > 0, 'SFPY: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve, ) = getReserves(); // gas savings require(amountOut < _reserve, 'SFPY: INSUFFICIENT_LIQUIDITY'); require(to != _token, 'SFPY: INVALID_TO'); if (amountOut > 0) _safeTransfer(to, amountOut); // optimistically transfer tokens ISfpyBorrower(to).borrow(msg.sender, amountOut, data); uint256 balance = ISfpyERC20(_token).balanceOf(address(this)); uint256 amountIn = balance > _reserve - amountOut ? balance - (_reserve - amountOut) : 0; require(amountIn > 0, 'SFPY: ZERO_INPUT_AMOUNT'); uint256 feeAmount = amountOut.mul(10 ** 15) / (10 ** 18); // .1% fee (10 ** 15 / 10*18) require(amountIn >= amountOut.add(feeAmount), 'SFPY: INSUFFICIENT_INPUT_AMOUNT'); require(balance >= _reserve, 'SFPY: INSUFFICIENT BALANCE'); _update(balance); } /// @dev returns the address of the factory function factory() external view returns (address) { return _factory; } /// @dev returns the underlying ERC-20 token of this pool function token() external view returns (address) { return _token; } }
mints liquidity tokens pro rata based on the amount of the underlying ERC-20 token that was transferred to the pool to the address to mint the liquidity tokens to
function mint(address to) external lock returns (uint256 liquidity) { uint256 balance = ISfpyERC20(_token).balanceOf(address(this)); uint256 amount = balance.sub(_reserve); uint256 _ts = totalSupply(); if (_ts == 0) { liquidity = Math.sqrt(amount.mul(ETHER)); liquidity = amount.mul(ETHER) / _ts; } require(liquidity > 0, 'SFPY: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance); emit Mint(msg.sender, amount); }
12,828,073
./full_match/3/0x4617ECf911B81471936F38E458f99E798EB3813a/sources/browser/index.sol
JPYC 0xdde5c1d6766cc56ed4be9922ad2c512dde4eafae
interface IERC20 { 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); }
14,164,755
./full_match/1/0xAa85F347B25Fb61175fF7d89A5cB79674249E7b9/sources/contracts/periphery/manager/PoolManagerUpdatable.sol
Restricted delta update mechanism/
function changeDelta(uint128 /*newDelta_*/ ) external pure override { revert PoolManagerUnsupportedOperation(); }
9,803,238
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@powerpool/power-oracle/contracts/interfaces/IPowerPoke.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IYearnVaultV2.sol"; import "../interfaces/PowerIndexPoolControllerInterface.sol"; import "../interfaces/ICurveDepositor.sol"; import "../interfaces/ICurveDepositor2.sol"; import "../interfaces/ICurveDepositor3.sol"; import "../interfaces/ICurveDepositor4.sol"; import "../interfaces/ICurveZapDepositor.sol"; import "../interfaces/ICurveZapDepositor2.sol"; import "../interfaces/ICurveZapDepositor3.sol"; import "../interfaces/ICurveZapDepositor4.sol"; import "../interfaces/ICurvePoolRegistry.sol"; import "./blocks/SinglePoolManagement.sol"; import "./WeightValueChangeRateAbstract.sol"; contract YearnVaultInstantRebindStrategy is SinglePoolManagement, WeightValueChangeRateAbstract { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 internal constant COMPENSATION_PLAN_1_ID = 1; event ChangePoolTokens(address[] poolTokensBefore, address[] poolTokensAfter); event InstantRebind(uint256 poolCurrentTokensCount, uint256 usdcPulled, uint256 usdcRemainder); event UpdatePool(address[] poolTokensBefore, address[] poolTokensAfter); event VaultWithdrawFee(address indexed vaultToken, uint256 crvAmount); event SeizeERC20(address indexed token, address indexed to, uint256 amount); event SetMaxWithdrawalLoss(uint256 maxWithdrawalLoss); event SetMinPulledUSDC(uint256 minPulledUSDC); event PullLiquidity( address indexed vaultToken, address crvToken, uint256 vaultAmount, uint256 crvAmountExpected, uint256 crvAmountActual, uint256 usdcAmount, uint256 vaultReserve ); event PushLiquidity( address indexed vaultToken, address crvToken, uint256 vaultAmount, uint256 crvAmount, uint256 usdcAmount ); event SetPoolController(address indexed poolController); event SetCurvePoolRegistry(address curvePoolRegistry); event SetVaultConfig( address indexed vault, address indexed depositor, uint8 depositorType, uint8 depositorTokenLength, int8 usdcIndex ); event SetStrategyConstraints(uint256 minUSDCRemainder, bool useVirtualPriceEstimation); struct RebindConfig { address token; uint256 newWeight; uint256 oldBalance; uint256 newBalance; } struct VaultConfig { address depositor; uint8 depositorType; uint8 depositorTokenLength; int8 usdcIndex; } struct StrategyConstraints { uint256 minUSDCRemainder; bool useVirtualPriceEstimation; } struct PullDataHelper { address crvToken; uint256 yDiff; uint256 ycrvBalance; uint256 crvExpected; uint256 crvActual; uint256 usdcBefore; uint256 vaultReserve; } IERC20 public immutable USDC; IPowerPoke public powerPoke; ICurvePoolRegistry public curvePoolRegistry; uint256 public lastUpdate; uint256 public maxWithdrawalLoss; StrategyConstraints public constraints; address[] internal poolTokens; mapping(address => VaultConfig) public vaultConfig; uint256 public minPulledUSDC; modifier onlyEOA() { require(msg.sender == tx.origin, "ONLY_EOA"); _; } modifier onlyReporter(uint256 _reporterId, bytes calldata _rewardOpts) { uint256 gasStart = gasleft(); powerPoke.authorizeReporter(_reporterId, msg.sender); _; _reward(_reporterId, gasStart, COMPENSATION_PLAN_1_ID, _rewardOpts); } modifier onlyNonReporter(uint256 _reporterId, bytes calldata _rewardOpts) { uint256 gasStart = gasleft(); powerPoke.authorizeNonReporter(_reporterId, msg.sender); _; _reward(_reporterId, gasStart, COMPENSATION_PLAN_1_ID, _rewardOpts); } constructor(address _pool, address _usdc) public SinglePoolManagement(_pool) OwnableUpgradeSafe() { USDC = IERC20(_usdc); } function initialize( address _powerPoke, address _curvePoolRegistry, address _poolController, uint256 _maxWithdrawalLoss, StrategyConstraints memory _constraints ) external initializer { __Ownable_init(); __SinglePoolManagement_init(_poolController); maxWithdrawalLoss = _maxWithdrawalLoss; powerPoke = IPowerPoke(_powerPoke); curvePoolRegistry = ICurvePoolRegistry(_curvePoolRegistry); constraints = _constraints; totalWeight = 25 * BONE; } /*** GETTERS ***/ function getTVL(PowerIndexPoolInterface, address _token) public view override returns (uint256) { return getVaultVirtualPriceEstimation(_token, IYearnVaultV2(_token).totalAssets()); } function getVaultVirtualPriceEstimation(address _token, uint256 _amount) public view returns (uint256) { return bmul( ICurvePoolRegistry(curvePoolRegistry).get_virtual_price_from_lp_token(IYearnVaultV2(_token).token()), _amount ); } function getVaultUsdcEstimation( address _token, address _crvToken, uint256 _amount ) public returns (uint256) { VaultConfig memory vc = vaultConfig[_token]; if (vc.depositorType == 2) { return ICurveZapDepositor(vc.depositor).calc_withdraw_one_coin(_crvToken, _amount, int128(vc.usdcIndex)); } else { return ICurveDepositor(vc.depositor).calc_withdraw_one_coin(_amount, int128(vc.usdcIndex)); } } function getPoolTokens() public view returns (address[] memory) { return poolTokens; } /*** OWNER'S SETTERS ***/ function setCurvePoolRegistry(address _curvePoolRegistry) external onlyOwner { curvePoolRegistry = ICurvePoolRegistry(_curvePoolRegistry); emit SetCurvePoolRegistry(_curvePoolRegistry); } function setVaultConfig( address _vault, address _depositor, uint8 _depositorType, uint8 _depositorTokenLength, int8 _usdcIndex ) external onlyOwner { vaultConfig[_vault] = VaultConfig(_depositor, _depositorType, _depositorTokenLength, _usdcIndex); IERC20 crvToken = IERC20(IYearnVaultV2(_vault).token()); _checkApprove(USDC.approve(_depositor, uint256(-1))); _checkApprove(crvToken.approve(_vault, uint256(-1))); _checkApprove(crvToken.approve(_depositor, uint256(-1))); emit SetVaultConfig(_vault, _depositor, _depositorType, _depositorTokenLength, _usdcIndex); } function setPoolController(address _poolController) public onlyOwner { poolController = _poolController; _updatePool(poolController, _poolController); emit SetPoolController(_poolController); } function syncPoolTokens() external onlyOwner { address controller = poolController; _updatePool(controller, controller); } function setMaxWithdrawalLoss(uint256 _maxWithdrawalLoss) external onlyOwner { maxWithdrawalLoss = _maxWithdrawalLoss; emit SetMaxWithdrawalLoss(_maxWithdrawalLoss); } function setMinPulledUSDC(uint256 _minPulledUSDC) external onlyOwner { minPulledUSDC = _minPulledUSDC; emit SetMinPulledUSDC(_minPulledUSDC); } function removeApprovals(IERC20[] calldata _tokens, address[] calldata _tos) external onlyOwner { uint256 len = _tokens.length; for (uint256 i = 0; i < len; i++) { _checkApprove(_tokens[i].approve(_tos[i], uint256(0))); } } function seizeERC20( address[] calldata _tokens, address[] calldata _tos, uint256[] calldata _amounts ) external onlyOwner { uint256 len = _tokens.length; require(len == _tos.length && len == _amounts.length, "LENGTHS"); for (uint256 i = 0; i < len; i++) { IERC20(_tokens[i]).safeTransfer(_tos[i], _amounts[i]); emit SeizeERC20(_tokens[i], _tos[i], _amounts[i]); } } function setStrategyConstraints(StrategyConstraints memory _constraints) external onlyOwner { constraints = _constraints; emit SetStrategyConstraints(_constraints.minUSDCRemainder, _constraints.useVirtualPriceEstimation); } function _checkApprove(bool _result) internal { require(_result, "APPROVE_FAILED"); } function _updatePool(address _oldController, address _newController) internal { address[] memory poolTokensBefore = poolTokens; uint256 len = poolTokensBefore.length; if (_oldController != address(0)) { // remove approval for (uint256 i = 0; i < len; i++) { _removeApprovalVault(poolTokensBefore[i], address(_oldController)); } } address[] memory poolTokensAfter = PowerIndexPoolInterface(pool).getCurrentTokens(); poolTokens = poolTokensAfter; // approve len = poolTokensAfter.length; for (uint256 i = 0; i < len; i++) { _approveVault(poolTokensAfter[i], address(_newController)); } emit UpdatePool(poolTokensBefore, poolTokensAfter); } function _approveVault(address _vaultToken, address _controller) internal { IERC20 vaultToken = IERC20(_vaultToken); _checkApprove(vaultToken.approve(pool, uint256(-1))); _checkApprove(vaultToken.approve(_controller, uint256(-1))); } function _removeApprovalVault(address _vaultToken, address _controller) internal { IERC20 vaultToken = IERC20(_vaultToken); _checkApprove(vaultToken.approve(pool, uint256(0))); _checkApprove(vaultToken.approve(_controller, uint256(0))); } function changePoolTokens(address[] memory _newTokens) external onlyOwner { address[] memory _currentTokens = BPoolInterface(pool).getCurrentTokens(); uint256 cLen = _currentTokens.length; uint256 nLen = _newTokens.length; for (uint256 i = 0; i < cLen; i++) { bool existsInNewTokens = false; for (uint256 j = 0; j < nLen; j++) { if (_currentTokens[i] == _newTokens[j]) { existsInNewTokens = true; } } if (!existsInNewTokens) { PowerIndexPoolControllerInterface(poolController).unbindByStrategy(_currentTokens[i]); _vaultToUsdc(_currentTokens[i], IYearnVaultV2(_currentTokens[i]).token(), vaultConfig[_currentTokens[i]]); _removeApprovalVault(_currentTokens[i], address(poolController)); } } for (uint256 j = 0; j < nLen; j++) { if (!BPoolInterface(pool).isBound(_newTokens[j])) { _approveVault(_newTokens[j], address(poolController)); } } _instantRebind(_newTokens, true); emit ChangePoolTokens(_currentTokens, _newTokens); } /*** POKERS ***/ function pokeFromReporter(uint256 _reporterId, bytes calldata _rewardOpts) external onlyReporter(_reporterId, _rewardOpts) onlyEOA { _poke(false); } function pokeFromSlasher(uint256 _reporterId, bytes calldata _rewardOpts) external onlyNonReporter(_reporterId, _rewardOpts) onlyEOA { _poke(true); } function _poke(bool _bySlasher) internal { (uint256 minInterval, uint256 maxInterval) = _getMinMaxReportInterval(); require(lastUpdate + minInterval < block.timestamp, "MIN_INTERVAL_NOT_REACHED"); if (_bySlasher) { require(lastUpdate + maxInterval < block.timestamp, "MAX_INTERVAL_NOT_REACHED"); } lastUpdate = block.timestamp; _instantRebind(BPoolInterface(pool).getCurrentTokens(), false); } function _vaultToUsdc( address _token, address _crvToken, VaultConfig memory _vc ) internal returns ( uint256 crvBalance, uint256 crvReceived, uint256 usdcBefore ) { crvBalance = IERC20(_token).balanceOf(address(this)); uint256 crvBefore = IERC20(_crvToken).balanceOf(address(this)); IYearnVaultV2(_token).withdraw(crvBalance, address(this), maxWithdrawalLoss); crvReceived = IERC20(_crvToken).balanceOf(address(this)).sub(crvBefore); usdcBefore = USDC.balanceOf(address(this)); if (_vc.depositorType == 2) { ICurveZapDepositor(_vc.depositor).remove_liquidity_one_coin(_crvToken, crvReceived, _vc.usdcIndex, 0); } else { ICurveDepositor(_vc.depositor).remove_liquidity_one_coin(crvReceived, _vc.usdcIndex, 0); } } function _usdcToVault( address _token, VaultConfig memory _vc, uint256 _usdcAmount ) internal returns ( uint256 crvBalance, uint256 vaultBalance, address crvToken ) { crvToken = IYearnVaultV2(_token).token(); _addUSDC2CurvePool(crvToken, _vc, _usdcAmount); // 2nd step. Vault.deposit() crvBalance = IERC20(crvToken).balanceOf(address(this)); IYearnVaultV2(_token).deposit(crvBalance); // 3rd step. Rebind vaultBalance = IERC20(_token).balanceOf(address(this)); } function _instantRebind(address[] memory _tokens, bool _allowNotBound) internal { address poolController_ = poolController; require(poolController_ != address(0), "CFG_NOT_SET"); RebindConfig[] memory configs = fetchRebindConfigs(PowerIndexPoolInterface(pool), _tokens, _allowNotBound); uint256 toPushUSDCTotal; uint256 len = configs.length; uint256[] memory toPushUSDC = new uint256[](len); VaultConfig[] memory vaultConfigs = new VaultConfig[](len); for (uint256 si = 0; si < len; si++) { RebindConfig memory cfg = configs[si]; VaultConfig memory vc = vaultConfig[cfg.token]; vaultConfigs[si] = vc; require(vc.depositor != address(0), "DEPOSIT_CONTRACT_NOT_SET"); if (cfg.newBalance <= cfg.oldBalance) { PullDataHelper memory mem; mem.crvToken = IYearnVaultV2(cfg.token).token(); mem.vaultReserve = IERC20(mem.crvToken).balanceOf(cfg.token); mem.yDiff = (cfg.oldBalance - cfg.newBalance); // 1st step. Rebind PowerIndexPoolControllerInterface(poolController_).rebindByStrategyRemove( cfg.token, cfg.newBalance, cfg.newWeight ); // 3rd step. CurvePool.remove_liquidity_one_coin() (mem.ycrvBalance, mem.crvActual, mem.usdcBefore) = _vaultToUsdc(cfg.token, mem.crvToken, vc); // 2nd step. Vault.withdraw() mem.crvExpected = bmul(mem.ycrvBalance, IYearnVaultV2(cfg.token).pricePerShare()); emit PullLiquidity( cfg.token, mem.crvToken, mem.yDiff, mem.crvExpected, mem.crvActual, USDC.balanceOf(address(this)) - mem.usdcBefore, mem.vaultReserve ); } else { uint256 yDiff = cfg.newBalance - cfg.oldBalance; uint256 crvAmount = IYearnVaultV2(cfg.token).pricePerShare().mul(yDiff) / 1e18; uint256 usdcIn; address crvToken = IYearnVaultV2(cfg.token).token(); if (constraints.useVirtualPriceEstimation) { uint256 virtualPrice = ICurvePoolRegistry(curvePoolRegistry).get_virtual_price_from_lp_token(crvToken); // usdcIn = virtualPrice * crvAmount / 1e18 usdcIn = bmul(virtualPrice, crvAmount); } else { usdcIn = getVaultUsdcEstimation(cfg.token, crvToken, crvAmount); } // toPushUSDCTotal += usdcIn; toPushUSDCTotal = toPushUSDCTotal.add(usdcIn); toPushUSDC[si] = usdcIn; } } uint256 usdcPulled = USDC.balanceOf(address(this)); require(usdcPulled > minPulledUSDC, "USDC_PULLED_NOT_ENOUGH"); for (uint256 si = 0; si < len; si++) { if (toPushUSDC[si] > 0) { RebindConfig memory cfg = configs[si]; // 1st step. Add USDC to Curve pool // uint256 usdcAmount = (usdcPulled * toPushUSDC[si]) / toPushUSDCTotal; uint256 usdcAmount = (usdcPulled.mul(toPushUSDC[si])) / toPushUSDCTotal; (uint256 crvBalance, uint256 vaultBalance, address crvToken) = _usdcToVault(cfg.token, vaultConfigs[si], usdcAmount); // uint256 newBalance = IERC20(cfg.token).balanceOf(address(this)) + BPoolInterface(_pool).getBalance(cfg.token) uint256 newBalance; try BPoolInterface(pool).getBalance(cfg.token) returns (uint256 _poolBalance) { newBalance = IERC20(cfg.token).balanceOf(address(this)).add(_poolBalance); } catch { newBalance = IERC20(cfg.token).balanceOf(address(this)); } if (cfg.oldBalance == 0) { require(_allowNotBound, "BIND_NOT_ALLOW"); PowerIndexPoolControllerInterface(poolController_).bindByStrategy(cfg.token, newBalance, cfg.newWeight); } else { PowerIndexPoolControllerInterface(poolController_).rebindByStrategyAdd( cfg.token, newBalance, cfg.newWeight, vaultBalance ); } emit PushLiquidity(cfg.token, crvToken, vaultBalance, crvBalance, usdcAmount); } } uint256 usdcRemainder = USDC.balanceOf(address(this)); require(usdcRemainder <= constraints.minUSDCRemainder, "USDC_REMAINDER"); emit InstantRebind(len, usdcPulled, usdcRemainder); } function fetchRebindConfigs( PowerIndexPoolInterface _pool, address[] memory _tokens, bool _allowNotBound ) internal returns (RebindConfig[] memory configs) { uint256 len = _tokens.length; (uint256[] memory oldBalances, uint256[] memory vaultUSDCPrices, uint256 totalUSDCPool) = getRebindConfigBalances(_pool, _tokens); (uint256[3][] memory weightsChange, , , uint256 totalValueUSDC) = computeWeightsChange(_pool, _tokens, new address[](0), 0, block.timestamp, block.timestamp + 1); configs = new RebindConfig[](len); for (uint256 si = 0; si < len; si++) { uint256[3] memory wc = weightsChange[si]; require(wc[1] != 0 || _allowNotBound, "TOKEN_NOT_BOUND"); configs[si] = RebindConfig( _tokens[wc[0]], // (totalWeight * newTokenValuesUSDC[oi]) / totalValueUSDC, wc[2], oldBalances[wc[0]], // (totalUSDCPool * weight / totalWeight) / vaultUSDCPrice) bdiv(bdiv(bmul(totalUSDCPool, wc[2]), totalWeight), vaultUSDCPrices[wc[0]]) ); } _updatePoolByPoke(pool, _tokens); } function getRebindConfigBalances(PowerIndexPoolInterface _pool, address[] memory _tokens) internal returns ( uint256[] memory oldBalances, uint256[] memory vaultUSDCPrices, uint256 totalUSDCPool ) { uint256 len = _tokens.length; oldBalances = new uint256[](len); vaultUSDCPrices = new uint256[](len); totalUSDCPool = USDC.balanceOf(address(this)) * 1e12; for (uint256 oi = 0; oi < len; oi++) { uint256 vaultUSDCPrice = bdiv( getVaultVirtualPriceEstimation(_tokens[oi], IYearnVaultV2(_tokens[oi]).totalAssets()), IERC20(_tokens[oi]).totalSupply() ); try PowerIndexPoolInterface(address(_pool)).getBalance(_tokens[oi]) returns (uint256 _balance) { oldBalances[oi] = _balance; totalUSDCPool = totalUSDCPool.add(bmul(oldBalances[oi], vaultUSDCPrice)); } catch { oldBalances[oi] = 0; } vaultUSDCPrices[oi] = vaultUSDCPrice; } } function _addUSDC2CurvePool( address _crvToken, VaultConfig memory _vc, uint256 _usdcAmount ) internal { if (_vc.depositorTokenLength == 2) { uint256[2] memory amounts; amounts[uint256(_vc.usdcIndex)] = _usdcAmount; if (_vc.depositorType == 2) { ICurveZapDepositor2(_vc.depositor).add_liquidity(_crvToken, amounts, 1); } else { ICurveDepositor2(_vc.depositor).add_liquidity(amounts, 1); } } if (_vc.depositorTokenLength == 3) { uint256[3] memory amounts; amounts[uint256(_vc.usdcIndex)] = _usdcAmount; if (_vc.depositorType == 2) { ICurveZapDepositor3(_vc.depositor).add_liquidity(_crvToken, amounts, 1); } else { ICurveDepositor3(_vc.depositor).add_liquidity(amounts, 1); } } if (_vc.depositorTokenLength == 4) { uint256[4] memory amounts; amounts[uint256(_vc.usdcIndex)] = _usdcAmount; if (_vc.depositorType == 2) { ICurveZapDepositor4(_vc.depositor).add_liquidity(_crvToken, amounts, 1); } else { ICurveDepositor4(_vc.depositor).add_liquidity(amounts, 1); } } } function _reward( uint256 _reporterId, uint256 _gasStart, uint256 _compensationPlan, bytes calldata _rewardOpts ) internal { powerPoke.reward(_reporterId, bsub(_gasStart, gasleft()), _compensationPlan, _rewardOpts); } function _getMinMaxReportInterval() internal view returns (uint256 min, uint256 max) { (uint256 minInterval, uint256 maxInterval) = powerPoke.getMinMaxReportIntervals(address(this)); require(minInterval > 0 && maxInterval > 0, "INTERVALS_ARE_0"); return (minInterval, maxInterval); } }
1st step. Rebind 3rd step. CurvePool.remove_liquidity_one_coin() 2nd step. Vault.withdraw() usdcIn = virtualPrice crvAmount / 1e18 1st step. Add USDC to Curve pool uint256 usdcAmount = (usdcPulled toPushUSDC[si]) / toPushUSDCTotal; uint256 newBalance = IERC20(cfg.token).balanceOf(address(this)) + BPoolInterface(_pool).getBalance(cfg.token)
function _instantRebind(address[] memory _tokens, bool _allowNotBound) internal { address poolController_ = poolController; require(poolController_ != address(0), "CFG_NOT_SET"); RebindConfig[] memory configs = fetchRebindConfigs(PowerIndexPoolInterface(pool), _tokens, _allowNotBound); uint256 toPushUSDCTotal; uint256 len = configs.length; uint256[] memory toPushUSDC = new uint256[](len); VaultConfig[] memory vaultConfigs = new VaultConfig[](len); for (uint256 si = 0; si < len; si++) { RebindConfig memory cfg = configs[si]; VaultConfig memory vc = vaultConfig[cfg.token]; vaultConfigs[si] = vc; require(vc.depositor != address(0), "DEPOSIT_CONTRACT_NOT_SET"); if (cfg.newBalance <= cfg.oldBalance) { PullDataHelper memory mem; mem.crvToken = IYearnVaultV2(cfg.token).token(); mem.vaultReserve = IERC20(mem.crvToken).balanceOf(cfg.token); mem.yDiff = (cfg.oldBalance - cfg.newBalance); PowerIndexPoolControllerInterface(poolController_).rebindByStrategyRemove( cfg.token, cfg.newBalance, cfg.newWeight ); (mem.ycrvBalance, mem.crvActual, mem.usdcBefore) = _vaultToUsdc(cfg.token, mem.crvToken, vc); mem.crvExpected = bmul(mem.ycrvBalance, IYearnVaultV2(cfg.token).pricePerShare()); emit PullLiquidity( cfg.token, mem.crvToken, mem.yDiff, mem.crvExpected, mem.crvActual, USDC.balanceOf(address(this)) - mem.usdcBefore, mem.vaultReserve ); uint256 yDiff = cfg.newBalance - cfg.oldBalance; uint256 crvAmount = IYearnVaultV2(cfg.token).pricePerShare().mul(yDiff) / 1e18; uint256 usdcIn; address crvToken = IYearnVaultV2(cfg.token).token(); if (constraints.useVirtualPriceEstimation) { uint256 virtualPrice = ICurvePoolRegistry(curvePoolRegistry).get_virtual_price_from_lp_token(crvToken); usdcIn = bmul(virtualPrice, crvAmount); usdcIn = getVaultUsdcEstimation(cfg.token, crvToken, crvAmount); } toPushUSDC[si] = usdcIn; } } uint256 usdcPulled = USDC.balanceOf(address(this)); require(usdcPulled > minPulledUSDC, "USDC_PULLED_NOT_ENOUGH"); for (uint256 si = 0; si < len; si++) { if (toPushUSDC[si] > 0) { RebindConfig memory cfg = configs[si]; uint256 usdcAmount = (usdcPulled.mul(toPushUSDC[si])) / toPushUSDCTotal; (uint256 crvBalance, uint256 vaultBalance, address crvToken) = _usdcToVault(cfg.token, vaultConfigs[si], usdcAmount); uint256 newBalance; try BPoolInterface(pool).getBalance(cfg.token) returns (uint256 _poolBalance) { newBalance = IERC20(cfg.token).balanceOf(address(this)).add(_poolBalance); newBalance = IERC20(cfg.token).balanceOf(address(this)); } if (cfg.oldBalance == 0) { require(_allowNotBound, "BIND_NOT_ALLOW"); PowerIndexPoolControllerInterface(poolController_).bindByStrategy(cfg.token, newBalance, cfg.newWeight); PowerIndexPoolControllerInterface(poolController_).rebindByStrategyAdd( cfg.token, newBalance, cfg.newWeight, vaultBalance ); } emit PushLiquidity(cfg.token, crvToken, vaultBalance, crvBalance, usdcAmount); } } uint256 usdcRemainder = USDC.balanceOf(address(this)); require(usdcRemainder <= constraints.minUSDCRemainder, "USDC_REMAINDER"); emit InstantRebind(len, usdcPulled, usdcRemainder); }
1,069,948
./full_match/4/0x2ca60d89144D4cdf85dA87af4FE12aBF9265F28C/sources/contracts/CustomMintRenameWithEth.sol
Send them back their ETH
function _allocateAndSweepRenameFee(uint256 tokenID, uint256 weiSent) private { if (freeRenameAvailable(tokenID)) { if (weiSent != 0) { _msgSender().transfer(weiSent); } return; } J_TYPE_EPOCH[ETH_ADDRESS] += 1; uint256 allocatableFee = ETH_RENAME_FEE - feeCollectorFeeAmount; uint256 remainderOfAllocation = allocatableFee % _totalShares; uint256 feePlusRemainder = feeCollectorFeeAmount + remainderOfAllocation; ownerAddress.transfer(feePlusRemainder); }
12,390,894
./partial_match/4/0x140649F2F1e2bE7ad08Cc0bCcf90C44840C9a581/sources/SocialBets.sol
Finish bet and pay to the winner or cancel if tie/
function finishBet( uint256 _betId, Answers _answer, BetFinishReasons _reason ) internal { Bet storage bet = bets[_betId]; address payable firstParty = bet.firstParty; address payable mediator = bet.mediator; address payable secondParty = bet.secondParty; uint256 firstBetValue = bet.firstBetValue; uint256 secondBetValue = bet.secondBetValue; address payable winner; uint256 mediatorFeeValue = 0; if (_reason == BetFinishReasons.MediatorFinished) { mediatorFeeValue = calculateMediatorFee(_betId); deleteMediatorActiveBet(mediator, _betId); } if (_answer == Answers.FirstPartyWins) { winner = firstParty; winner = secondParty; if (_reason == BetFinishReasons.MediatorFinished) { cancelBet(_betId, BetCancellationReasons.MediatorCancelled); cancelBet(_betId, BetCancellationReasons.Tie); } return; } delete bets[_betId]; deleteFirstPartyActiveBet(firstParty, _betId); deleteSecondPartyActiveBet(secondParty, _betId); winner.transfer(firstBetValue.add(secondBetValue).sub(mediatorFeeValue)); emit Finished(_betId, winner, _reason, firstBetValue.add(secondBetValue).sub(mediatorFeeValue)); emit Completed(firstParty, secondParty, mediator, _betId); }
8,504,053
./full_match/137/0x706347C8f492624BF2c8cE91A90Ee400D6DC03e8/sources/EOEO_NFT_flat.sol
concatenate the tokenID to the baseURI.
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory base = _baseURI(); return string(abi.encodePacked(base, tokenId.toString())); }
3,774,977
pragma solidity ^0.4.18; contract DragonCrowdsaleCore { function crowdsale( address _address )payable; function precrowdsale( address _address )payable; } contract Dragon { function transfer(address receiver, uint amount)returns(bool ok); function balanceOf( address _address )returns(uint256); } contract DragonCrowdsale { address public owner; Dragon tokenReward; bool public crowdSaleStarted; bool public crowdSaleClosed; bool public crowdSalePause; uint public deadline; address public CoreAddress; DragonCrowdsaleCore core; modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } function DragonCrowdsale(){ crowdSaleStarted = false; crowdSaleClosed = false; crowdSalePause = false; owner = msg.sender; tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); } // fallback function to receive all incoming ether funds and then forwarded to the DragonCrowdsaleCore contract function () payable { require ( crowdSaleClosed == false && crowdSalePause == false ); if ( crowdSaleStarted ) { require ( now < deadline ); core.crowdsale.value( msg.value )( msg.sender); // forward all ether to core contract } else { core.precrowdsale.value( msg.value )( msg.sender); } // forward all ether to core contract } // Start this to initiate crowdsale - will run for 60 days function startCrowdsale() onlyOwner { crowdSaleStarted = true; deadline = now + 60 days; } //terminates the crowdsale function endCrowdsale() onlyOwner { crowdSaleClosed = true; } //pauses the crowdsale function pauseCrowdsale() onlyOwner { crowdSalePause = true; } //unpauses the crowdsale function unpauseCrowdsale() onlyOwner { crowdSalePause = false; } // set the dragon crowdsalecore contract function setCore( address _core ) onlyOwner { require ( _core != 0x00 ); CoreAddress = _core; core = DragonCrowdsaleCore( _core ); } function transferOwnership( address _address ) onlyOwner { require ( _address!= 0x00 ); owner = _address ; } //emergency withdrawal of Dragons incase sent to this address function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( msg.sender , balance ); } }
Start this to initiate crowdsale - will run for 60 days
function startCrowdsale() onlyOwner { crowdSaleStarted = true; deadline = now + 60 days; }
6,472,516
pragma solidity ^0.4.18; /** * @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; } } pragma solidity ^0.4.18; /** * @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; } } contract Haltable is Ownable { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() public onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() public onlyOwner onlyInEmergency { halted = false; } } pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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]; } } pragma solidity ^0.4.18; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#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; } } /** * @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(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; } } /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @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) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } /** * Merit token */ contract MeritToken is CappedToken { event NewCap(uint256 value); string public constant name = "Merit Token"; // solium-disable-line uppercase string public constant symbol = "MERIT"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase bool public tokensReleased; function MeritToken(uint256 _cap) public CappedToken(_cap * 10**uint256(decimals)) { } modifier released { require(mintingFinished); _; } modifier notReleased { require(!mintingFinished); _; } // only allow these functions once the token is released (minting is done) // basically the zeppelin &#39;Pausable&#39; token but using my token release flag // Only allow our token to be usable once the minting phase is over function transfer(address _to, uint256 _value) public released returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public released returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public released returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public released returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public released returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } // for our token, the balance will always be zero if we&#39;re still minting them // once we&#39;re done minting, the tokens will be effectively released to their owners function balanceOf(address _owner) public view released returns (uint256 balance) { return super.balanceOf(_owner); } // lets us see the pre-allocated balance, since we&#39;re just letting the token keep track of all of the allocations // instead of going through another complete allocation step for all users function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } // revoke a user&#39;s tokens if they have been banned for violating the TOS. // Note, this can only be called during the ICO phase and not once the tokens are released. function revoke(address _owner) public onlyOwner notReleased returns (uint256 balance) { // the balance should never ben greater than our total supply, so don&#39;t worry about checking balance = balances[_owner]; balances[_owner] = 0; totalSupply_ = totalSupply_.sub(balance); } } contract MeritICO is Ownable, Haltable { using SafeMath for uint256; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // token MeritToken public token; address public reserveVault; address public restrictedVault; //address public fundWallet; enum Stage { None, Closed, PrivateSale, PreSale, Round1, Round2, Round3, Round4, Allocating, Done } Stage public currentStage; uint256 public tokenCap; uint256 public icoCap; uint256 public marketingCap; uint256 public teamCap; uint256 public reserveCap; // number of tokens per ether, kept with 3 decimals (so divide by 1000) uint public exchangeRate; uint public bonusRate; uint256 public currentSaleCap; uint256 public weiRaised; uint256 public baseTokensAllocated; uint256 public bonusTokensAllocated; bool public saleAllocated; struct Contribution { uint256 base; uint256 bonus; } // current base and bonus balances for each contributor mapping (address => Contribution) contributionBalance; // map of any address that has been banned from participating in the ICO, for violations of TOS mapping (address => bool) blacklist; modifier saleActive { require(currentStage > Stage.Closed && currentStage < Stage.Allocating); _; } modifier saleAllocatable { require(currentStage > Stage.Closed && currentStage <= Stage.Allocating); _; } modifier saleNotDone { require(currentStage != Stage.Done); _; } modifier saleAllocating { require (currentStage == Stage.Allocating); _; } modifier saleClosed { require (currentStage == Stage.Closed); _; } modifier saleDone { require (currentStage == Stage.Done); _; } // _token is the address of an already deployed MeritToken contract // // team tokens go into a restricted access vault // reserve tokens go into a reserve vault // any bonus or referral tokens come out of the marketing pool // any base purchased tokens come out of the ICO pool // all percentages are based off of the cap in the passed in token // // anything left over in the marketing or ico pool is burned // function MeritICO() public { //fundWallet = _fundWallet; currentStage = Stage.Closed; } function updateToken(address _token) external onlyOwner saleNotDone { require(_token != address(0)); token = MeritToken(_token); tokenCap = token.cap(); require(MeritToken(_token).owner() == address(this)); } function updateCaps(uint256 _icoPercent, uint256 _marketingPercent, uint256 _teamPercent, uint256 _reservePercent) external onlyOwner saleNotDone { require(_icoPercent + _marketingPercent + _teamPercent + _reservePercent == 100); uint256 max = tokenCap; marketingCap = max.mul(_marketingPercent).div(100); icoCap = max.mul(_icoPercent).div(100); teamCap = max.mul(_teamPercent).div(100); reserveCap = max.mul(_reservePercent).div(100); require (marketingCap + icoCap + teamCap + reserveCap == max); } function setStage(Stage _stage) public onlyOwner saleNotDone { // don&#39;t allow you to set the stage to done unless the tokens have been released require (_stage != Stage.Done || saleAllocated == true); currentStage = _stage; } function startAllocation() public onlyOwner saleActive { require (!saleAllocated); currentStage = Stage.Allocating; } // set how many tokens per wei, kept with 3 decimals function updateExchangeRate(uint _rateTimes1000) public onlyOwner saleNotDone { exchangeRate = _rateTimes1000; } // bonus rate percentage (value 0 to 100) // cap is the cumulative cap at this point in time function updateICO(uint _bonusRate, uint256 _cap, Stage _stage) external onlyOwner saleNotDone { require (_bonusRate <= 100); require(_cap <= icoCap); require(_stage != Stage.None); bonusRate = _bonusRate; currentSaleCap = _cap; currentStage = _stage; } function updateVaults(address _reserve, address _restricted) external onlyOwner saleNotDone { require(_reserve != address(0)); require(_restricted != address(0)); reserveVault = _reserve; restrictedVault = _restricted; require(Ownable(_reserve).owner() == address(this)); require(Ownable(_restricted).owner() == address(this)); } function updateReserveVault(address _reserve) external onlyOwner saleNotDone { require(_reserve != address(0)); reserveVault = _reserve; require(Ownable(_reserve).owner() == address(this)); } function updateRestrictedVault(address _restricted) external onlyOwner saleNotDone { require(_restricted != address(0)); restrictedVault = _restricted; require(Ownable(_restricted).owner() == address(this)); } //function updateFundWallet(address _wallet) external onlyOwner saleNotDone { // require(_wallet != address(0)); // require(fundWallet != _wallet); // fundWallet = _wallet; //} function bookkeep(address _beneficiary, uint256 _base, uint256 _bonus) internal returns(bool) { uint256 newBase = baseTokensAllocated.add(_base); uint256 newBonus = bonusTokensAllocated.add(_bonus); if (newBase > currentSaleCap || newBonus > marketingCap) { return false; } baseTokensAllocated = newBase; bonusTokensAllocated = newBonus; Contribution storage c = contributionBalance[_beneficiary]; c.base = c.base.add(_base); c.bonus = c.bonus.add(_bonus); return true; } function computeTokens(uint256 _weiAmount, uint _bonusRate) external view returns (uint256 base, uint256 bonus) { base = _weiAmount.mul(exchangeRate).div(1000); bonus = base.mul(_bonusRate).div(100); } // can only &#39;buy&#39; tokens while the sale is active. function () public payable saleActive stopInEmergency { revert(); //buyTokens(msg.sender); } //function buyTokens(address _beneficiary) public payable saleActive stopInEmergency { //require(msg.value != 0); //require(_beneficiary != 0x0); //require(blacklist[_beneficiary] == false); //uint256 weiAmount = msg.value; //uint256 baseTokens = weiAmount.mul(exchangeRate).div(1000); //uint256 bonusTokens = baseTokens.mul(bonusRate).div(100); //require (bookkeep(_beneficiary, baseTokens, bonusTokens)); //uint256 total = baseTokens.add(bonusTokens); //weiRaised = weiRaised.add(weiAmount); //TokenPurchase(msg.sender, _beneficiary, weiAmount, total); //fundWallet.transfer(weiAmount); //token.mint(_beneficiary, total); //} // function to purchase tokens for someone, from an external funding source. This function // assumes that the external source has been verified. bonus amount is passed in, so we can // handle an edge case where someone externally purchased tokens when the bonus should be different // than it currnetly is set to. function buyTokensFor(address _beneficiary, uint256 _baseTokens, uint _bonusTokens) external onlyOwner saleAllocatable { require(_beneficiary != 0x0); require(_baseTokens != 0 || _bonusTokens != 0); require(blacklist[_beneficiary] == false); require(bookkeep(_beneficiary, _baseTokens, _bonusTokens)); uint256 total = _baseTokens.add(_bonusTokens); TokenPurchase(msg.sender, _beneficiary, 0, total); token.mint(_beneficiary, total); } // same as above, but strictly for allocating tokens out of the bonus pool function giftTokens(address _beneficiary, uint256 _giftAmount) external onlyOwner saleAllocatable { require(_beneficiary != 0x0); require(_giftAmount != 0); require(blacklist[_beneficiary] == false); require(bookkeep(_beneficiary, 0, _giftAmount)); TokenPurchase(msg.sender, _beneficiary, 0, _giftAmount); token.mint(_beneficiary, _giftAmount); } function balanceOf(address _beneficiary) public view returns(uint256, uint256) { require(_beneficiary != address(0)); Contribution storage c = contributionBalance[_beneficiary]; return (c.base, c.bonus); } // ban/prevent a user from participating in the ICO for violations of TOS, and deallocate any tokens they have allocated // if any refunds are necessary, they are handled offline function ban(address _owner) external onlyOwner saleAllocatable returns (uint256 total) { require(_owner != address(0)); require(!blacklist[_owner]); uint256 base; uint256 bonus; (base, bonus) = balanceOf(_owner); delete contributionBalance[_owner]; baseTokensAllocated = baseTokensAllocated.sub(base); bonusTokensAllocated = bonusTokensAllocated.sub(bonus); blacklist[_owner] = true; total = token.revoke(_owner); } // unbans a user that was banned with the above function. does NOT reallocate their tokens function unban(address _beneficiary) external onlyOwner saleAllocatable { require(_beneficiary != address(0)); require(blacklist[_beneficiary] == true); delete blacklist[_beneficiary]; } // release any other tokens needed and mark us as allocated function releaseTokens() external onlyOwner saleAllocating { require(reserveVault != address(0)); require(restrictedVault != address(0)); require(saleAllocated == false); saleAllocated = true; // allocate the team and reserve tokens to our vaults token.mint(reserveVault, reserveCap); token.mint(restrictedVault, teamCap); } // end the ICO, tokens won&#39;t show up in anyone&#39;s wallets until this function is called. // once this is called, nothing works on the ICO any longer function endICO() external onlyOwner saleAllocating { require(saleAllocated); currentStage = Stage.Done; // this will release all allocated tokens to their owners token.finishMinting(); // now transfer all these objects back to our owner, which we know to be a trusted account token.transferOwnership(owner); Ownable(reserveVault).transferOwnership(owner); Ownable(restrictedVault).transferOwnership(owner); } function giveBack() public onlyOwner { if (address(token) != address(0)) token.transferOwnership(owner); if (reserveVault != address(0)) Ownable(reserveVault).transferOwnership(owner); if (restrictedVault != address(0)) Ownable(restrictedVault).transferOwnership(owner); } }
ban/prevent a user from participating in the ICO for violations of TOS, and deallocate any tokens they have allocated if any refunds are necessary, they are handled offline
function ban(address _owner) external onlyOwner saleAllocatable returns (uint256 total) { require(_owner != address(0)); require(!blacklist[_owner]); uint256 base; uint256 bonus; (base, bonus) = balanceOf(_owner); delete contributionBalance[_owner]; baseTokensAllocated = baseTokensAllocated.sub(base); bonusTokensAllocated = bonusTokensAllocated.sub(bonus); blacklist[_owner] = true; total = token.revoke(_owner); }
6,666,660
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./amm/interfaces/ITempusAMM.sol"; import "./amm/interfaces/IVault.sol"; import "./ITempusPool.sol"; import "./math/Fixed256xVar.sol"; import "./utils/AMMBalancesHelper.sol"; import "./utils/UntrustedERC20.sol"; import "./utils/Ownable.sol"; import "./utils/Versioned.sol"; /// @dev TempusController singleton with a transferrable ownership and re-entrancy guards /// Owner is automatically set to the deployer of this contract contract TempusController is ReentrancyGuard, Ownable, Versioned { using Fixed256xVar for uint256; using SafeERC20 for IERC20; using UntrustedERC20 for IERC20; using AMMBalancesHelper for uint256[]; /// Registry for valid pools and AMM's to avoid fake address injection mapping(address => bool) private registry; /// @dev Event emitted on a successful BT/YBT deposit. /// @param pool The Tempus Pool to which assets were deposited /// @param depositor Address of the user who deposited Yield Bearing Tokens to mint /// Tempus Principal Share (TPS) and Tempus Yield Shares /// @param recipient Address of the recipient who will receive TPS and TYS tokens /// @param yieldTokenAmount Amount of yield tokens received from underlying pool /// @param backingTokenValue Value of @param yieldTokenAmount expressed in backing tokens /// @param shareAmounts Number of Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) granted to `recipient` /// @param interestRate Interest Rate of the underlying pool from Yield Bearing Tokens to the underlying asset /// @param fee The fee which was deducted (in terms of yield bearing tokens) event Deposited( address indexed pool, address indexed depositor, address indexed recipient, uint256 yieldTokenAmount, uint256 backingTokenValue, uint256 shareAmounts, uint256 interestRate, uint256 fee ); /// @dev Event emitted on a successful BT/YBT redemption. /// @param pool The Tempus Pool from which Tempus Shares were redeemed /// @param redeemer Address of the user whose Shares (Principals and Yields) are redeemed /// @param recipient Address of user that received Yield Bearing Tokens /// @param principalShareAmount Number of Tempus Principal Shares (TPS) to redeem into the Yield Bearing Token (YBT) /// @param yieldShareAmount Number of Tempus Yield Shares (TYS) to redeem into the Yield Bearing Token (YBT) /// @param yieldTokenAmount Number of Yield bearing tokens redeemed from the pool /// @param backingTokenValue Value of @param yieldTokenAmount expressed in backing tokens /// @param interestRate Interest Rate of the underlying pool from Yield Bearing Tokens to the underlying asset /// @param fee The fee which was deducted (in terms of yield bearing tokens) /// @param isEarlyRedeem True in case of early redemption, otherwise false event Redeemed( address indexed pool, address indexed redeemer, address indexed recipient, uint256 principalShareAmount, uint256 yieldShareAmount, uint256 yieldTokenAmount, uint256 backingTokenValue, uint256 interestRate, uint256 fee, bool isEarlyRedeem ); constructor() Versioned(1, 0, 0) {} /// @dev Registers a POOL or an AMM as valid or invalid to use with this Controller /// @param authorizedContract Contract which will be allowed to be used inside this Controller /// @param isValid If true, contract is valid to be used, if false, it's not allowed anymore function register(address authorizedContract, bool isValid) public onlyOwner { registry[authorizedContract] = isValid; } /// @dev Validates that the provided contract is registered to be used with this Controller /// @param authorizedContract Contract address to check function requireRegistered(address authorizedContract) private view { require(registry[authorizedContract], "Unauthorized contract address"); } /// @dev Atomically deposits YBT/BT to TempusPool and provides liquidity /// to the corresponding Tempus AMM with the issued TYS & TPS /// @param tempusAMM Tempus AMM to use to swap TYS for TPS /// @param tokenAmount Amount of YBT/BT to be deposited /// @param isBackingToken specifies whether the deposited asset is the Backing Token or Yield Bearing Token function depositAndProvideLiquidity( ITempusAMM tempusAMM, uint256 tokenAmount, bool isBackingToken ) external payable nonReentrant { requireRegistered(address(tempusAMM)); _depositAndProvideLiquidity(tempusAMM, tokenAmount, isBackingToken); } /// @dev Adds liquidity to tempusAMM with ratio of shares that is equal to ratio in AMM /// @param tempusAMM Tempus AMM to provide liquidity to /// @param sharesAmount Amount of shares to be used to provide liquidity, one of the sahres will be partially used /// @notice If sharesAmount is 100 and amm balances ratio is 1 principal : 10 yields 90 principal will be "unused" /// So, liquidity will be provided with 10 principals and 100 yields /// @notice msg.sender needs to approve Controller for both Principals and Yields for @param sharesAmount function provideLiquidity(ITempusAMM tempusAMM, uint256 sharesAmount) external nonReentrant { requireRegistered(address(tempusAMM)); ( IVault vault, bytes32 poolId, IERC20[] memory ammTokens, uint256[] memory ammBalances ) = _getAMMDetailsAndEnsureInitialized(tempusAMM); _provideLiquidity(msg.sender, vault, poolId, ammTokens, ammBalances, sharesAmount, msg.sender); } /// @dev Atomically deposits YBT/BT to TempusPool and swaps TYS for TPS to get fixed yield /// See https://docs.balancer.fi/developers/guides/single-swaps#swap-overview /// @param tempusAMM Tempus AMM to use to swap TYS for TPS /// @param tokenAmount Amount of YBT/BT to be deposited in underlying YBT/BT decimal precision /// @param isBackingToken specifies whether the deposited asset is the Backing Token or Yield Bearing Token /// @param minTYSRate Minimum exchange rate of TYS (denominated in TPS) to receive in exchange for TPS /// @param deadline A timestamp by which the transaction must be completed, otherwise it would revert function depositAndFix( ITempusAMM tempusAMM, uint256 tokenAmount, bool isBackingToken, uint256 minTYSRate, uint256 deadline ) external payable nonReentrant { requireRegistered(address(tempusAMM)); _depositAndFix(tempusAMM, tokenAmount, isBackingToken, minTYSRate, deadline); } /// @dev Deposits Yield Bearing Tokens to a Tempus Pool. /// @param targetPool The Tempus Pool to which tokens will be deposited /// @param yieldTokenAmount amount of Yield Bearing Tokens to be deposited /// in YBT Contract precision which can be 18 or 8 decimals /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) function depositYieldBearing( ITempusPool targetPool, uint256 yieldTokenAmount, address recipient ) external nonReentrant { require(recipient != address(0), "recipient can not be 0x0"); requireRegistered(address(targetPool)); _depositYieldBearing(targetPool, yieldTokenAmount, recipient); } /// @dev Deposits Backing Tokens into the underlying protocol and /// then deposited the minted Yield Bearing Tokens to the Tempus Pool. /// @param targetPool The Tempus Pool to which tokens will be deposited /// @param backingTokenAmount amount of Backing Tokens to be deposited into the underlying protocol /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) function depositBacking( ITempusPool targetPool, uint256 backingTokenAmount, address recipient ) external payable nonReentrant { require(recipient != address(0), "recipient can not be 0x0"); requireRegistered(address(targetPool)); _depositBacking(targetPool, backingTokenAmount, recipient); } /// @dev Redeem TPS+TYS held by msg.sender into Yield Bearing Tokens /// @notice `msg.sender` will receive yield bearing tokens /// @notice Before maturity, `principalAmount` must equal to `yieldAmount` /// @param targetPool The Tempus Pool from which to redeem Tempus Shares /// @param principalAmount Amount of Tempus Principals to redeem in PrincipalShare decimal precision /// @param yieldAmount Amount of Tempus Yields to redeem in YieldShare decimal precision /// @param recipient Address of user that will receive yield bearing tokens function redeemToYieldBearing( ITempusPool targetPool, uint256 principalAmount, uint256 yieldAmount, address recipient ) external nonReentrant { require(recipient != address(0), "recipient can not be 0x0"); requireRegistered(address(targetPool)); _redeemToYieldBearing(targetPool, msg.sender, principalAmount, yieldAmount, recipient); } /// @dev Redeem TPS+TYS held by msg.sender into Backing Tokens /// @notice `recipient` will receive the backing tokens /// @notice Before maturity, `principalAmount` must equal to `yieldAmount` /// @param targetPool The Tempus Pool from which to redeem Tempus Shares /// @param principalAmount Amount of Tempus Principals to redeem in PrincipalShare decimal precision /// @param yieldAmount Amount of Tempus Yields to redeem in YieldShare decimal precision /// @param recipient Address of user that will receive yield bearing tokens function redeemToBacking( ITempusPool targetPool, uint256 principalAmount, uint256 yieldAmount, address recipient ) external nonReentrant { require(recipient != address(0), "recipient can not be 0x0"); requireRegistered(address(targetPool)); _redeemToBacking(targetPool, msg.sender, principalAmount, yieldAmount, recipient); } /// @dev Withdraws liquidity from TempusAMM /// @notice `msg.sender` needs to approve controller for @param lpTokensAmount of LP tokens /// @notice Transfers LP tokens to controller and exiting tempusAmm with `msg.sender` as recipient /// @param tempusAMM Tempus AMM instance /// @param lpTokensAmount Amount of LP tokens to be withdrawn /// @param principalAmountOutMin Minimal amount of TPS to be withdrawn /// @param yieldAmountOutMin Minimal amount of TYS to be withdrawn /// @param toInternalBalances Withdrawing liquidity to internal balances function exitTempusAMM( ITempusAMM tempusAMM, uint256 lpTokensAmount, uint256 principalAmountOutMin, uint256 yieldAmountOutMin, bool toInternalBalances ) external nonReentrant { requireRegistered(address(tempusAMM)); _exitTempusAMM(tempusAMM, lpTokensAmount, principalAmountOutMin, yieldAmountOutMin, toInternalBalances); } /// @dev Withdraws liquidity from TempusAMM and redeems Shares to Yield Bearing or Backing Tokens /// Checks user's balance of principal shares and yield shares /// and exits AMM with exact amounts needed for redemption. /// @notice `msg.sender` needs to approve controller for whole balance of LP token /// @notice Transfers users' LP tokens to controller, then exits tempusAMM with `msg.sender` as recipient. /// After exit transfers remainder of LP tokens back to user /// @notice Can fail if there is not enough user balance /// @notice Only available before maturity since exiting AMM with exact amounts is disallowed after maturity /// @param tempusAMM TempusAMM instance to withdraw liquidity from /// @param principals Amount of Principals to redeem /// @param yields Amount of Yields to redeem /// @param principalsStaked Amount of staked principals (in TempusAMM) to redeem /// @param yieldsStaked Amount of staked yields (in TempusAMM) to redeem /// @param maxLpTokensToRedeem Maximum amount of LP tokens to spend for staked shares redemption /// @param toBackingToken If true redeems to backing token, otherwise redeems to yield bearing function exitAmmGivenAmountsOutAndEarlyRedeem( ITempusAMM tempusAMM, uint256 principals, uint256 yields, uint256 principalsStaked, uint256 yieldsStaked, uint256 maxLpTokensToRedeem, bool toBackingToken ) external nonReentrant { requireRegistered(address(tempusAMM)); _exitAmmGivenAmountsOutAndEarlyRedeem( tempusAMM, principals, yields, principalsStaked, yieldsStaked, maxLpTokensToRedeem, toBackingToken ); } /// @dev Withdraws ALL liquidity from TempusAMM and redeems Shares to Yield Bearing or Backing Tokens /// @notice `msg.sender` needs to approve controller for whole balance of LP token /// @notice Can fail if there is not enough user balance /// @param tempusAMM TempusAMM instance to withdraw liquidity from /// @param lpTokens Number of Lp tokens to redeem /// @param principals Number of Principals to redeem /// @param yields Number of Yields to redeem /// @param minPrincipalsStaked Minimum amount of staked principals to redeem for `lpTokens` /// @param minYieldsStaked Minimum amount of staked yields to redeem for `lpTokens` /// @param maxLeftoverShares Maximum amount of Principals or Yields to be left in case of early exit /// @param yieldsRate Base exchange rate of TYS (denominated in TPS) /// @param maxSlippage Maximum allowed change in the exchange rate from the base @param yieldsRate (1e18 precision) /// @param toBackingToken If true redeems to backing token, otherwise redeems to yield bearing /// @param deadline A timestamp by which, if a swap is necessary, the transaction must be completed, /// otherwise it would revert function exitAmmGivenLpAndRedeem( ITempusAMM tempusAMM, uint256 lpTokens, uint256 principals, uint256 yields, uint256 minPrincipalsStaked, uint256 minYieldsStaked, uint256 maxLeftoverShares, uint256 yieldsRate, uint256 maxSlippage, bool toBackingToken, uint256 deadline ) external nonReentrant { requireRegistered(address(tempusAMM)); if (lpTokens > 0) { // if there is LP balance, transfer to controller require(tempusAMM.transferFrom(msg.sender, address(this), lpTokens), "LP token transfer failed"); // exit amm and sent shares to controller uint256[] memory minAmountsOutFromLP = getAMMOrderedAmounts( tempusAMM, minPrincipalsStaked, minYieldsStaked ); _exitTempusAMMGivenLP(tempusAMM, address(this), address(this), lpTokens, minAmountsOutFromLP, false); } _redeemWithEqualShares( tempusAMM, principals, yields, maxLeftoverShares, yieldsRate, maxSlippage, deadline, toBackingToken ); } function swap( ITempusAMM tempusAMM, uint256 swapAmount, IERC20 tokenIn, IERC20 tokenOut, uint256 minReturn, uint256 deadline ) private { require(swapAmount > 0, "Invalid swap amount."); tokenIn.safeIncreaseAllowance(address(tempusAMM.getVault()), swapAmount); (IVault vault, bytes32 poolId, , ) = _getAMMDetailsAndEnsureInitialized(tempusAMM); IVault.SingleSwap memory singleSwap = IVault.SingleSwap({ poolId: poolId, kind: IVault.SwapKind.GIVEN_IN, assetIn: tokenIn, assetOut: tokenOut, amount: swapAmount, userData: "" }); IVault.FundManagement memory fundManagement = IVault.FundManagement({ sender: address(this), fromInternalBalance: false, recipient: payable(address(this)), toInternalBalance: false }); vault.swap(singleSwap, fundManagement, minReturn, deadline); } function _depositAndProvideLiquidity( ITempusAMM tempusAMM, uint256 tokenAmount, bool isBackingToken ) private { ( IVault vault, bytes32 poolId, IERC20[] memory ammTokens, uint256[] memory ammBalances ) = _getAMMDetailsAndEnsureInitialized(tempusAMM); uint256 mintedShares = _deposit(tempusAMM.tempusPool(), tokenAmount, isBackingToken); uint256[] memory sharesUsed = _provideLiquidity( address(this), vault, poolId, ammTokens, ammBalances, mintedShares, msg.sender ); // Send remaining Shares to user if (mintedShares > sharesUsed[0]) { ammTokens[0].safeTransfer(msg.sender, mintedShares - sharesUsed[0]); } if (mintedShares > sharesUsed[1]) { ammTokens[1].safeTransfer(msg.sender, mintedShares - sharesUsed[1]); } } function _provideLiquidity( address sender, IVault vault, bytes32 poolId, IERC20[] memory ammTokens, uint256[] memory ammBalances, uint256 sharesAmount, address recipient ) private returns (uint256[] memory) { uint256[] memory ammLiquidityProvisionAmounts = ammBalances.getLiquidityProvisionSharesAmounts(sharesAmount); if (sender != address(this)) { ammTokens[0].safeTransferFrom(sender, address(this), ammLiquidityProvisionAmounts[0]); ammTokens[1].safeTransferFrom(sender, address(this), ammLiquidityProvisionAmounts[1]); } ammTokens[0].safeIncreaseAllowance(address(vault), ammLiquidityProvisionAmounts[0]); ammTokens[1].safeIncreaseAllowance(address(vault), ammLiquidityProvisionAmounts[1]); IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: ammTokens, maxAmountsIn: ammLiquidityProvisionAmounts, userData: abi.encode(uint8(ITempusAMM.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT), ammLiquidityProvisionAmounts), fromInternalBalance: false }); // Provide TPS/TYS liquidity to TempusAMM vault.joinPool(poolId, address(this), recipient, request); return ammLiquidityProvisionAmounts; } function _depositAndFix( ITempusAMM tempusAMM, uint256 tokenAmount, bool isBackingToken, uint256 minTYSRate, uint256 deadline ) private { ITempusPool targetPool = tempusAMM.tempusPool(); IERC20 principalShares = IERC20(address(targetPool.principalShare())); IERC20 yieldShares = IERC20(address(targetPool.yieldShare())); uint256 swapAmount = _deposit(targetPool, tokenAmount, isBackingToken); yieldShares.safeIncreaseAllowance(address(tempusAMM.getVault()), swapAmount); uint256 minReturn = swapAmount.mulfV(minTYSRate, targetPool.backingTokenONE()); swap(tempusAMM, swapAmount, yieldShares, principalShares, minReturn, deadline); // At this point all TYS must be swapped for TPS uint256 principalsBalance = principalShares.balanceOf(address(this)); assert(principalsBalance > 0); principalShares.safeTransfer(msg.sender, principalsBalance); } function _deposit( ITempusPool targetPool, uint256 tokenAmount, bool isBackingToken ) private returns (uint256 mintedShares) { mintedShares = isBackingToken ? _depositBacking(targetPool, tokenAmount, address(this)) : _depositYieldBearing(targetPool, tokenAmount, address(this)); } function _depositYieldBearing( ITempusPool targetPool, uint256 yieldTokenAmount, address recipient ) private returns (uint256) { require(yieldTokenAmount > 0, "yieldTokenAmount is 0"); IERC20 yieldBearingToken = IERC20(targetPool.yieldBearingToken()); // Transfer funds from msg.sender to targetPool uint transferredYBT = yieldBearingToken.untrustedTransferFrom( msg.sender, address(targetPool), yieldTokenAmount ); (uint mintedShares, uint depositedBT, uint fee, uint rate) = targetPool.onDepositYieldBearing( transferredYBT, recipient ); emit Deposited( address(targetPool), msg.sender, recipient, transferredYBT, depositedBT, mintedShares, rate, fee ); return mintedShares; } function _depositBacking( ITempusPool targetPool, uint256 backingTokenAmount, address recipient ) private returns (uint256) { require(backingTokenAmount > 0, "backingTokenAmount is 0"); IERC20 backingToken = IERC20(targetPool.backingToken()); // In case the underlying pool expects deposits in Ether (e.g. Lido), // it uses `backingToken = address(0)`. Since we disallow 0-value deposits, // and `msg.value == backingTokenAmount`, this check here can be used to // distinguish between the two pool types. if (msg.value == 0) { // NOTE: We need to have this check here to avoid calling transfer on address(0), // because that always succeeds. require(address(backingToken) != address(0), "Pool requires ETH deposits"); backingTokenAmount = backingToken.untrustedTransferFrom( msg.sender, address(targetPool), backingTokenAmount ); } else { require(address(backingToken) == address(0), "given TempusPool's Backing Token is not ETH"); require(msg.value == backingTokenAmount, "ETH value does not match provided amount"); } (uint256 mintedShares, uint256 depositedYBT, uint256 fee, uint256 interestRate) = targetPool.onDepositBacking{ value: msg.value }(backingTokenAmount, recipient); emit Deposited( address(targetPool), msg.sender, recipient, depositedYBT, backingTokenAmount, mintedShares, interestRate, fee ); return mintedShares; } function _redeemToYieldBearing( ITempusPool targetPool, address sender, uint256 principals, uint256 yields, address recipient ) private { require((principals > 0) || (yields > 0), "principalAmount and yieldAmount cannot both be 0"); (uint redeemedYBT, uint fee, uint interestRate) = targetPool.redeem(sender, principals, yields, recipient); uint redeemedBT = targetPool.numAssetsPerYieldToken(redeemedYBT, targetPool.currentInterestRate()); bool earlyRedeem = !targetPool.matured(); emit Redeemed( address(targetPool), sender, recipient, principals, yields, redeemedYBT, redeemedBT, fee, interestRate, earlyRedeem ); } function _redeemToBacking( ITempusPool targetPool, address sender, uint256 principals, uint256 yields, address recipient ) private { require((principals > 0) || (yields > 0), "principalAmount and yieldAmount cannot both be 0"); (uint redeemedYBT, uint redeemedBT, uint fee, uint rate) = targetPool.redeemToBacking( sender, principals, yields, recipient ); bool earlyRedeem = !targetPool.matured(); emit Redeemed( address(targetPool), sender, recipient, principals, yields, redeemedYBT, redeemedBT, fee, rate, earlyRedeem ); } function _exitTempusAMM( ITempusAMM tempusAMM, uint256 lpTokensAmount, uint256 principalAmountOutMin, uint256 yieldAmountOutMin, bool toInternalBalances ) private { require(tempusAMM.transferFrom(msg.sender, address(this), lpTokensAmount), "LP token transfer failed"); uint256[] memory amounts = getAMMOrderedAmounts(tempusAMM, principalAmountOutMin, yieldAmountOutMin); _exitTempusAMMGivenLP(tempusAMM, address(this), msg.sender, lpTokensAmount, amounts, toInternalBalances); } function _exitTempusAMMGivenLP( ITempusAMM tempusAMM, address sender, address recipient, uint256 lpTokensAmount, uint256[] memory minAmountsOut, bool toInternalBalances ) private { require(lpTokensAmount > 0, "LP token amount is 0"); (IVault vault, bytes32 poolId, IERC20[] memory ammTokens, ) = _getAMMDetailsAndEnsureInitialized(tempusAMM); IVault.ExitPoolRequest memory request = IVault.ExitPoolRequest({ assets: ammTokens, minAmountsOut: minAmountsOut, userData: abi.encode(uint8(ITempusAMM.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT), lpTokensAmount), toInternalBalance: toInternalBalances }); vault.exitPool(poolId, sender, payable(recipient), request); } function _exitTempusAMMGivenAmountsOut( ITempusAMM tempusAMM, address sender, address recipient, uint256[] memory amountsOut, uint256 lpTokensAmountInMax, bool toInternalBalances ) private { (IVault vault, bytes32 poolId, IERC20[] memory ammTokens, ) = _getAMMDetailsAndEnsureInitialized(tempusAMM); IVault.ExitPoolRequest memory request = IVault.ExitPoolRequest({ assets: ammTokens, minAmountsOut: amountsOut, userData: abi.encode( uint8(ITempusAMM.ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT), amountsOut, lpTokensAmountInMax ), toInternalBalance: toInternalBalances }); vault.exitPool(poolId, sender, payable(recipient), request); } function _exitAmmGivenAmountsOutAndEarlyRedeem( ITempusAMM tempusAMM, uint256 principals, uint256 yields, uint256 principalsStaked, uint256 yieldsStaked, uint256 maxLpTokensToRedeem, bool toBackingToken ) private { ITempusPool tempusPool = tempusAMM.tempusPool(); require(!tempusPool.matured(), "Pool already finalized"); principals += principalsStaked; yields += yieldsStaked; require(principals == yields, "Needs equal amounts of shares before maturity"); // transfer LP tokens to controller require(tempusAMM.transferFrom(msg.sender, address(this), maxLpTokensToRedeem), "LP token transfer failed"); uint256[] memory amounts = getAMMOrderedAmounts(tempusAMM, principalsStaked, yieldsStaked); _exitTempusAMMGivenAmountsOut(tempusAMM, address(this), msg.sender, amounts, maxLpTokensToRedeem, false); // transfer remainder of LP tokens back to user uint256 lpTokenBalance = tempusAMM.balanceOf(address(this)); require(tempusAMM.transferFrom(address(this), msg.sender, lpTokenBalance), "LP token transfer failed"); if (toBackingToken) { _redeemToBacking(tempusPool, msg.sender, principals, yields, msg.sender); } else { _redeemToYieldBearing(tempusPool, msg.sender, principals, yields, msg.sender); } } function _redeemWithEqualShares( ITempusAMM tempusAMM, uint256 principals, uint256 yields, uint256 maxLeftoverShares, uint256 yieldsRate, uint256 maxSlippage, uint256 deadline, bool toBackingToken ) private { ITempusPool tempusPool = tempusAMM.tempusPool(); IERC20 principalShare = IERC20(address(tempusPool.principalShare())); IERC20 yieldShare = IERC20(address(tempusPool.yieldShare())); require(principalShare.transferFrom(msg.sender, address(this), principals), "Principals transfer failed"); require(yieldShare.transferFrom(msg.sender, address(this), yields), "Yields transfer failed"); require(yieldsRate > 0, "yieldsRate must be greater than 0"); require(maxSlippage <= 1e18, "maxSlippage can not be greater than 1e18"); principals = principalShare.balanceOf(address(this)); yields = yieldShare.balanceOf(address(this)); if (!tempusPool.matured()) { if (((yields > principals) ? (yields - principals) : (principals - yields)) >= maxLeftoverShares) { (uint256 swapAmount, bool yieldsIn) = tempusAMM.getSwapAmountToEndWithEqualShares( principals, yields, maxLeftoverShares ); uint256 minReturn = yieldsIn ? swapAmount.mulfV(yieldsRate, tempusPool.backingTokenONE()) : swapAmount.divfV(yieldsRate, tempusPool.backingTokenONE()); minReturn = minReturn.mulfV(1e18 - maxSlippage, 1e18); swap( tempusAMM, swapAmount, yieldsIn ? yieldShare : principalShare, yieldsIn ? principalShare : yieldShare, minReturn, deadline ); principals = principalShare.balanceOf(address(this)); yields = yieldShare.balanceOf(address(this)); } (yields, principals) = (principals <= yields) ? (principals, principals) : (yields, yields); } if (toBackingToken) { _redeemToBacking(tempusPool, address(this), principals, yields, msg.sender); } else { _redeemToYieldBearing(tempusPool, address(this), principals, yields, msg.sender); } } function _getAMMDetailsAndEnsureInitialized(ITempusAMM tempusAMM) private view returns ( IVault vault, bytes32 poolId, IERC20[] memory ammTokens, uint256[] memory ammBalances ) { vault = tempusAMM.getVault(); poolId = tempusAMM.getPoolId(); (ammTokens, ammBalances, ) = vault.getPoolTokens(poolId); require( ammTokens.length == 2 && ammBalances.length == 2 && ammBalances[0] > 0 && ammBalances[1] > 0, "AMM not initialized" ); } function getAMMOrderedAmounts( ITempusAMM tempusAMM, uint256 principalAmount, uint256 yieldAmount ) private view returns (uint256[] memory) { IVault vault = tempusAMM.getVault(); (IERC20[] memory ammTokens, , ) = vault.getPoolTokens(tempusAMM.getPoolId()); uint256[] memory amounts = new uint256[](2); (amounts[0], amounts[1]) = (address(tempusAMM.tempusPool().principalShare()) == address(ammTokens[0])) ? (principalAmount, yieldAmount) : (yieldAmount, principalAmount); return amounts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: BUSL-1.1 pragma solidity >=0.7.0; import "./IVault.sol"; import "./../../ITempusPool.sol"; interface ITempusAMM { enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT } function getVault() external view returns (IVault); function getPoolId() external view returns (bytes32); function tempusPool() external view returns (ITempusPool); function balanceOf(address) external view returns (uint256); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /// Calculates the expected returned swap amount /// @param amount The given input amount of tokens /// @param yieldShareIn Specifies whether to calculate the swap from TYS to TPS (if true) or from TPS to TYS /// @return The expected returned amount of outToken function getExpectedReturnGivenIn(uint256 amount, bool yieldShareIn) external view returns (uint256); /// @dev Returns amount that user needs to swap to end up with almost the same amounts of Principals and Yields /// @param principals User's Principals balance /// @param yields User's Yields balance /// @param threshold Maximum difference between final balances of Principals and Yields /// @return amountIn Amount of Principals or Yields that user needs to swap to end with almost equal amounts /// @return yieldsIn Specifies the "direction" of the swap - /// whether Yields should be swapped for Principals (yieldsIn=true) or vice versa function getSwapAmountToEndWithEqualShares( uint256 principals, uint256 yields, uint256 threshold ) external view returns (uint256 amountIn, bool yieldsIn); /// @dev queries exiting TempusAMM with exact BPT tokens in /// @param bptAmountIn amount of LP tokens in /// @return principals Amount of principals that user would receive back /// @return yields Amount of yields that user would receive back function getExpectedTokensOutGivenBPTIn(uint256 bptAmountIn) external view returns (uint256 principals, uint256 yields); /// @dev queries exiting TempusAMM with exact tokens out /// @param principalsStaked amount of Principals to withdraw /// @param yieldsStaked amount of Yields to withdraw /// @return lpTokens Amount of Lp tokens that user would redeem function getExpectedBPTInGivenTokensOut(uint256 principalsStaked, uint256 yieldsStaked) external view returns (uint256 lpTokens); /// @dev queries joining TempusAMM with exact tokens in /// @param amountsIn amount of tokens to be added to the pool /// @return amount of LP tokens that could be received function getExpectedLPTokensForTokensIn(uint256[] memory amountsIn) external view returns (uint256); /// @dev This function returns the appreciation of one BPT relative to the /// underlying tokens. This starts at 1 when the pool is created and grows over time function getRate() external view returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IVault { enum SwapKind { GIVEN_IN, GIVEN_OUT } struct SingleSwap { bytes32 poolId; SwapKind kind; IERC20 assetIn; IERC20 assetOut; uint256 amount; bytes userData; } struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } struct JoinPoolRequest { IERC20[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } struct ExitPoolRequest { IERC20[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.7.6 <0.9.0; pragma abicoder v2; import "./token/IPoolShare.sol"; import "./utils/IOwnable.sol"; import "./utils/IVersioned.sol"; /// Setting and transferring of fees are restricted to the owner. interface ITempusFees is IOwnable { /// The fees are in terms of yield bearing token (YBT). struct FeesConfig { uint256 depositPercent; uint256 earlyRedeemPercent; uint256 matureRedeemPercent; } /// Returns the current fee configuration. function getFeesConfig() external view returns (FeesConfig memory); /// Replace the current fee configuration with a new one. /// By default all the fees are expected to be set to zero. /// @notice This function can only be called by the owner. function setFeesConfig(FeesConfig calldata newFeesConfig) external; /// @return Maximum possible fee percentage that can be set for deposit function maxDepositFee() external view returns (uint256); /// @return Maximum possible fee percentage that can be set for early redeem function maxEarlyRedeemFee() external view returns (uint256); /// @return Maximum possible fee percentage that can be set for mature redeem function maxMatureRedeemFee() external view returns (uint256); /// Accumulated fees available for withdrawal. function totalFees() external view returns (uint256); /// Transfers accumulated Yield Bearing Token (YBT) fees /// from this pool contract to `recipient`. /// @param recipient Address which will receive the specified amount of YBT /// @notice This function can only be called by the owner. function transferFees(address recipient) external; } /// All state changing operations are restricted to the controller. interface ITempusPool is ITempusFees, IVersioned { /// @return The name of underlying protocol, for example "Aave" for Aave protocol function protocolName() external view returns (bytes32); /// This token will be used as a token that user can deposit to mint same amounts /// of principal and interest shares. /// @return The underlying yield bearing token. function yieldBearingToken() external view returns (address); /// This is the address of the actual backing asset token /// in the case of ETH, this address will be 0 /// @return Address of the Backing Token function backingToken() external view returns (address); /// @return uint256 value of one backing token, in case of 18 decimals 1e18 function backingTokenONE() external view returns (uint256); /// @return This TempusPool's Tempus Principal Share (TPS) function principalShare() external view returns (IPoolShare); /// @return This TempusPool's Tempus Yield Share (TYS) function yieldShare() external view returns (IPoolShare); /// @return The TempusController address that is authorized to perform restricted actions function controller() external view returns (address); /// @return Start time of the pool. function startTime() external view returns (uint256); /// @return Maturity time of the pool. function maturityTime() external view returns (uint256); /// @return Time of exceptional halting of the pool. /// In case the pool is still in operation, this must return type(uint256).max. function exceptionalHaltTime() external view returns (uint256); /// @return The maximum allowed time (in seconds) to pass with negative yield. function maximumNegativeYieldDuration() external view returns (uint256); /// @return True if maturity has been reached and the pool was finalized. /// This also includes the case when maturity was triggered due to /// exceptional conditions (negative yield periods). function matured() external view returns (bool); /// Finalizes the pool. This can only happen on or after `maturityTime`. /// Once finalized depositing is not possible anymore, and the behaviour /// redemption will change. /// /// Can be called by anyone and can be called multiple times. function finalize() external; /// Yield bearing tokens deposit hook. /// @notice Deposit will fail if maturity has been reached. /// @notice This function can only be called by TempusController /// @notice This function assumes funds were already transferred to the TempusPool from the TempusController /// @param yieldTokenAmount Amount of yield bearing tokens to deposit in YieldToken decimal precision /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) /// @return mintedShares Amount of TPS and TYS minted to `recipient` /// @return depositedBT The YBT value deposited, denominated as Backing Tokens /// @return fee The fee which was deducted (in terms of YBT) /// @return rate The interest rate at the time of the deposit function onDepositYieldBearing(uint256 yieldTokenAmount, address recipient) external returns ( uint256 mintedShares, uint256 depositedBT, uint256 fee, uint256 rate ); /// Backing tokens deposit hook. /// @notice Deposit will fail if maturity has been reached. /// @notice This function can only be called by TempusController /// @notice This function assumes funds were already transferred to the TempusPool from the TempusController /// @param backingTokenAmount amount of Backing Tokens to be deposited to underlying protocol in BackingToken decimal precision /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) /// @return mintedShares Amount of TPS and TYS minted to `recipient` /// @return depositedYBT The BT value deposited, denominated as Yield Bearing Tokens /// @return fee The fee which was deducted (in terms of YBT) /// @return rate The interest rate at the time of the deposit function onDepositBacking(uint256 backingTokenAmount, address recipient) external payable returns ( uint256 mintedShares, uint256 depositedYBT, uint256 fee, uint256 rate ); /// Redeems yield bearing tokens from this TempusPool /// msg.sender will receive the YBT /// NOTE #1 Before maturity, principalAmount must equal to yieldAmount. /// NOTE #2 This function can only be called by TempusController /// @param from Address to redeem its Tempus Shares /// @param principalAmount Amount of Tempus Principal Shares (TPS) to redeem for YBT in PrincipalShare decimal precision /// @param yieldAmount Amount of Tempus Yield Shares (TYS) to redeem for YBT in YieldShare decimal precision /// @param recipient Address to which redeemed YBT will be sent /// @return redeemableYieldTokens Amount of Yield Bearing Tokens redeemed to `recipient` /// @return fee The fee which was deducted (in terms of YBT) /// @return rate The interest rate at the time of the redemption function redeem( address from, uint256 principalAmount, uint256 yieldAmount, address recipient ) external returns ( uint256 redeemableYieldTokens, uint256 fee, uint256 rate ); /// Redeems TPS+TYS held by msg.sender into backing tokens /// `msg.sender` must approve TPS and TYS amounts to this TempusPool. /// `msg.sender` will receive the backing tokens /// NOTE #1 Before maturity, principalAmount must equal to yieldAmount. /// NOTE #2 This function can only be called by TempusController /// @param from Address to redeem its Tempus Shares /// @param principalAmount Amount of Tempus Principal Shares (TPS) to redeem in PrincipalShare decimal precision /// @param yieldAmount Amount of Tempus Yield Shares (TYS) to redeem in YieldShare decimal precision /// @param recipient Address to which redeemed BT will be sent /// @return redeemableYieldTokens Amount of Backing Tokens redeemed to `recipient`, denominated in YBT /// @return redeemableBackingTokens Amount of Backing Tokens redeemed to `recipient` /// @return fee The fee which was deducted (in terms of YBT) /// @return rate The interest rate at the time of the redemption function redeemToBacking( address from, uint256 principalAmount, uint256 yieldAmount, address recipient ) external payable returns ( uint256 redeemableYieldTokens, uint256 redeemableBackingTokens, uint256 fee, uint256 rate ); /// Gets the estimated amount of Principals and Yields after a successful deposit /// @param amount Amount of BackingTokens or YieldBearingTokens that would be deposited /// @param isBackingToken If true, @param amount is in BackingTokens, otherwise YieldBearingTokens /// @return Amount of Principals (TPS) and Yields (TYS) in Principal/YieldShare decimal precision /// TPS and TYS are minted in 1:1 ratio, hence a single return value. function estimatedMintedShares(uint256 amount, bool isBackingToken) external view returns (uint256); /// Gets the estimated amount of YieldBearingTokens or BackingTokens received when calling `redeemXXX()` functions /// @param principals Amount of Principals (TPS) in PrincipalShare decimal precision /// @param yields Amount of Yields (TYS) in YieldShare decimal precision /// @param toBackingToken If true, redeem amount is estimated in BackingTokens instead of YieldBearingTokens /// @return Amount of YieldBearingTokens or BackingTokens in YBT/BT decimal precision function estimatedRedeem( uint256 principals, uint256 yields, bool toBackingToken ) external view returns (uint256); /// @dev This returns the stored Interest Rate of the YBT (Yield Bearing Token) pool /// it is safe to call this after updateInterestRate() was called /// @return Stored Interest Rate, decimal precision depends on specific TempusPool implementation function currentInterestRate() external view returns (uint256); /// @return Initial interest rate of the underlying pool, /// decimal precision depends on specific TempusPool implementation function initialInterestRate() external view returns (uint256); /// @return Interest rate at maturity of the underlying pool (or 0 if maturity not reached yet) /// decimal precision depends on specific TempusPool implementation function maturityInterestRate() external view returns (uint256); /// @return Rate of one Tempus Yield Share expressed in Asset Tokens function pricePerYieldShare() external returns (uint256); /// @return Rate of one Tempus Principal Share expressed in Asset Tokens function pricePerPrincipalShare() external returns (uint256); /// Calculated with stored interest rates /// @return Rate of one Tempus Yield Share expressed in Asset Tokens, function pricePerYieldShareStored() external view returns (uint256); /// Calculated with stored interest rates /// @return Rate of one Tempus Principal Share expressed in Asset Tokens function pricePerPrincipalShareStored() external view returns (uint256); /// @dev This returns actual Backing Token amount for amount of YBT (Yield Bearing Tokens) /// For example, in case of Aave and Lido the result is 1:1, /// and for compound is `yieldTokens * currentInterestRate` /// @param yieldTokens Amount of YBT in YBT decimal precision /// @param interestRate The current interest rate /// @return Amount of Backing Tokens for specified @param yieldTokens function numAssetsPerYieldToken(uint yieldTokens, uint interestRate) external view returns (uint); /// @dev This returns amount of YBT (Yield Bearing Tokens) that can be converted /// from @param backingTokens Backing Tokens /// @param backingTokens Amount of Backing Tokens in BT decimal precision /// @param interestRate The current interest rate /// @return Amount of YBT for specified @param backingTokens function numYieldTokensPerAsset(uint backingTokens, uint interestRate) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; /// @dev Fixed Point decimal math utils for variable decimal point precision /// on 256-bit wide numbers library Fixed256xVar { /// @dev Multiplies two variable precision fixed point decimal numbers /// @param one 1.0 expressed in the base precision of `a` and `b` /// @return result = a * b function mulfV( uint256 a, uint256 b, uint256 one ) internal pure returns (uint256) { // result is always truncated return (a * b) / one; } /// @dev Divides two variable precision fixed point decimal numbers /// @param one 1.0 expressed in the base precision of `a` and `b` /// @return result = a / b function divfV( uint256 a, uint256 b, uint256 one ) internal pure returns (uint256) { // result is always truncated return (a * one) / b; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import "../math/Fixed256xVar.sol"; library AMMBalancesHelper { using Fixed256xVar for uint256; uint256 internal constant ONE = 1e18; function getLiquidityProvisionSharesAmounts(uint256[] memory ammBalances, uint256 shares) internal pure returns (uint256[] memory) { uint256[2] memory ammDepositPercentages = getAMMBalancesRatio(ammBalances); uint256[] memory ammLiquidityProvisionAmounts = new uint256[](2); (ammLiquidityProvisionAmounts[0], ammLiquidityProvisionAmounts[1]) = ( shares.mulfV(ammDepositPercentages[0], ONE), shares.mulfV(ammDepositPercentages[1], ONE) ); return ammLiquidityProvisionAmounts; } function getAMMBalancesRatio(uint256[] memory ammBalances) internal pure returns (uint256[2] memory balancesRatio) { uint256 rate = ammBalances[0].divfV(ammBalances[1], ONE); (balancesRatio[0], balancesRatio[1]) = rate > ONE ? (ONE, ONE.divfV(rate, ONE)) : (rate, ONE); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title UntrustedERC20 /// @dev Wrappers around ERC20 transfer operators that return the actual amount /// transferred. This means they are usable with tokens, which charge a fee or royalty on transfer. library UntrustedERC20 { using SafeERC20 for IERC20; /// Transfer tokens to a recipient. /// @param token The ERC20 token. /// @param to The recipient. /// @param value The requested amount. /// @return The actual amount of tokens transferred. function untrustedTransfer( IERC20 token, address to, uint256 value ) internal returns (uint256) { uint256 startBalance = token.balanceOf(to); token.safeTransfer(to, value); return token.balanceOf(to) - startBalance; } /// Transfer tokens to a recipient. /// @param token The ERC20 token. /// @param from The sender. /// @param to The recipient. /// @param value The requested amount. /// @return The actual amount of tokens transferred. function untrustedTransferFrom( IERC20 token, address from, address to, uint256 value ) internal returns (uint256) { uint256 startBalance = token.balanceOf(to); token.safeTransferFrom(from, to, value); return token.balanceOf(to) - startBalance; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./IOwnable.sol"; /// Implements Ownable with a two step transfer of ownership abstract contract Ownable is IOwnable { address private _owner; address private _proposedOwner; /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual override returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Proposes a transfer of ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual override onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _proposedOwner = newOwner; emit OwnershipProposed(_owner, _proposedOwner); } /** * @dev Accepts ownership of the contract by a proposed account. * Can only be called by the proposed owner. */ function acceptOwnership() public virtual override { require(msg.sender == _proposedOwner, "Ownable: Only proposed owner can accept ownership"); _setOwner(_proposedOwner); _proposedOwner = address(0); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9.0; import "./IVersioned.sol"; /// Implements versioning abstract contract Versioned is IVersioned { uint16 private immutable _major; uint16 private immutable _minor; uint16 private immutable _patch; constructor( uint16 major, uint16 minor, uint16 patch ) { _major = major; _minor = minor; _patch = patch; } function version() external view returns (Version memory) { return Version(_major, _minor, _patch); } } // 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: BUSL-1.1 pragma solidity >=0.7.6 <0.9.0; import "../ITempusPool.sol"; /// Interface of Tokens representing the principal or yield shares of a pool. interface IPoolShare { enum ShareKind { Principal, Yield } /// @return The kind of the share. function kind() external view returns (ShareKind); /// @return The pool this share is part of. function pool() external view returns (ITempusPool); /// @dev Price per single share expressed in Backing Tokens of the underlying pool. /// This is for the purpose of TempusAMM api support. /// Example: exchanging Tempus Yield Share to DAI /// @return 1e18 decimal conversion rate per share function getPricePerFullShare() external returns (uint256); /// @return 1e18 decimal stored conversion rate per share function getPricePerFullShareStored() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9.0; /// Implements Ownable with a two step transfer of ownership interface IOwnable { /** * @dev Change of ownership proposed. * @param currentOwner The current owner. * @param proposedOwner The proposed owner. */ event OwnershipProposed(address indexed currentOwner, address indexed proposedOwner); /** * @dev Ownership transferred. * @param previousOwner The previous owner. * @param newOwner The new owner. */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current owner. */ function owner() external view returns (address); /** * @dev Proposes a transfer of ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external; /** * @dev Accepts ownership of the contract by a proposed account. * Can only be called by the proposed owner. */ function acceptOwnership() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9.0; pragma abicoder v2; /// Implements versioning interface IVersioned { struct Version { uint16 major; uint16 minor; uint16 patch; } /// @return The version of the contract. function version() external view returns (Version memory); }
Transfer tokens to a recipient. token The ERC20 token. from The sender. to The recipient. value The requested amount. return The actual amount of tokens transferred.
function untrustedTransferFrom( IERC20 token, address from, address to, uint256 value ) internal returns (uint256) { uint256 startBalance = token.balanceOf(to); token.safeTransferFrom(from, to, value); return token.balanceOf(to) - startBalance; }
1,804,521
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6; pragma experimental ABIEncoderV2; import "./DeploymentConstants.sol"; import "./interfaces/IKyberNetwork.sol"; import "./ApproximateBuys.sol"; import "./SamplerUtils.sol"; contract KyberSampler is DeploymentConstants, SamplerUtils, ApproximateBuys { /// @dev Gas limit for Kyber calls. uint256 constant private KYBER_CALL_GAS = 500e3; // 500k /// @dev Sample sell quotes from Kyber. /// @param reserveOffset The nth reserve /// @param takerToken Address of the taker token (what to sell). /// @param makerToken Address of the maker token (what to buy). /// @param takerTokenAmounts Taker token sell amount for each sample. /// @return reserveId The id of the reserve found at reserveOffset /// @return hint The hint for the selected reserve /// @return makerTokenAmounts Maker amounts bought at each taker token amount. function sampleSellsFromKyberNetwork( uint256 reserveOffset, address takerToken, address makerToken, uint256[] memory takerTokenAmounts ) public view returns (bytes32 reserveId, bytes memory hint, uint256[] memory makerTokenAmounts) { _assertValidPair(makerToken, takerToken); reserveId = _getNextReserveId(takerToken, makerToken, reserveOffset); if (reserveId == 0x0) { return (reserveId, hint, makerTokenAmounts); } hint = this.encodeKyberHint(reserveId, takerToken, makerToken); uint256 numSamples = takerTokenAmounts.length; makerTokenAmounts = new uint256[](numSamples); for (uint256 i = 0; i < numSamples; i++) { uint256 value = this.sampleSellFromKyberNetwork( hint, takerToken, makerToken, takerTokenAmounts[i] ); // Return early if the source has no liquidity if (value == 0) { return (reserveId, hint, makerTokenAmounts); } makerTokenAmounts[i] = value; } } /// @dev Sample buy quotes from Kyber. /// @param reserveOffset The nth reserve /// @param takerToken Address of the taker token (what to sell). /// @param makerToken Address of the maker token (what to buy). /// @param makerTokenAmounts Maker token buy amount for each sample. /// @return reserveId The id of the reserve found at reserveOffset /// @return hint The hint for the selected reserve /// @return takerTokenAmounts Taker amounts sold at each maker token amount. function sampleBuysFromKyberNetwork( uint256 reserveOffset, address takerToken, address makerToken, uint256[] memory makerTokenAmounts ) public view returns (bytes32 reserveId, bytes memory hint, uint256[] memory takerTokenAmounts) { _assertValidPair(makerToken, takerToken); reserveId = _getNextReserveId(takerToken, makerToken, reserveOffset); if (reserveId == 0x0) { return (reserveId, hint, takerTokenAmounts); } hint = this.encodeKyberHint(reserveId, takerToken, makerToken); takerTokenAmounts = _sampleApproximateBuys( ApproximateBuyQuoteOpts({ makerTokenData: abi.encode(makerToken, hint), takerTokenData: abi.encode(takerToken, hint), getSellQuoteCallback: _sampleSellForApproximateBuyFromKyber }), makerTokenAmounts ); return (reserveId, hint, takerTokenAmounts); } function encodeKyberHint( bytes32 reserveId, address takerToken, address makerToken ) public view returns (bytes memory hint) { // Build a hint selecting the single reserve IKyberHintHandler kyberHint = IKyberHintHandler(_getKyberHintHandlerAddress()); // All other reserves should be ignored with this hint bytes32[] memory selectedReserves = new bytes32[](1); selectedReserves[0] = reserveId; uint256[] memory emptySplits = new uint256[](0); if (takerToken == _getWethAddress()) { // ETH to Token try kyberHint.buildEthToTokenHint {gas: KYBER_CALL_GAS} ( makerToken, IKyberHintHandler.TradeType.MaskIn, selectedReserves, emptySplits ) returns (bytes memory result) { return result; } catch (bytes memory) { // Swallow failures, leaving all results as zero. } } else if (makerToken == _getWethAddress()) { // Token to ETH try kyberHint.buildTokenToEthHint {gas: KYBER_CALL_GAS} ( takerToken, IKyberHintHandler.TradeType.MaskIn, selectedReserves, emptySplits ) returns (bytes memory result) { return result; } catch (bytes memory) { // Swallow failures, leaving all results as zero. } } else { // Token to Token // We use the same reserve both ways try kyberHint.buildTokenToTokenHint {gas: KYBER_CALL_GAS} ( takerToken, IKyberHintHandler.TradeType.MaskIn, selectedReserves, emptySplits, makerToken, IKyberHintHandler.TradeType.MaskIn, selectedReserves, emptySplits ) returns (bytes memory result) { return result; } catch (bytes memory) { // Swallow failures, leaving all results as zero. } } } function _sampleSellForApproximateBuyFromKyber( bytes memory takerTokenData, bytes memory makerTokenData, uint256 sellAmount ) private view returns (uint256) { (address makerToken, bytes memory hint) = abi.decode(makerTokenData, (address, bytes)); (address takerToken, ) = abi.decode(takerTokenData, (address, bytes)); try this.sampleSellFromKyberNetwork (hint, takerToken, makerToken, sellAmount) returns (uint256 amount) { return amount; } catch (bytes memory) { // Swallow failures, leaving all results as zero. return 0; } } function sampleSellFromKyberNetwork( bytes memory hint, address takerToken, address makerToken, uint256 takerTokenAmount ) public view returns (uint256 makerTokenAmount) { // If there is no hint do not continue if (hint.length == 0) { return 0; } try IKyberNetworkProxy(_getKyberNetworkProxyAddress()).getExpectedRateAfterFee {gas: KYBER_CALL_GAS} ( takerToken == _getWethAddress() ? KYBER_ETH_ADDRESS : takerToken, makerToken == _getWethAddress() ? KYBER_ETH_ADDRESS : makerToken, takerTokenAmount, 0, // fee hint ) returns (uint256 rate) { uint256 makerTokenDecimals = _getTokenDecimals(makerToken); uint256 takerTokenDecimals = _getTokenDecimals(takerToken); makerTokenAmount = rate * takerTokenAmount * 10 ** makerTokenDecimals / 10 ** takerTokenDecimals / 10 ** 18; return makerTokenAmount; } catch (bytes memory) { // Swallow failures, leaving all results as zero. return 0; } } function _getNextReserveId( address takerToken, address makerToken, uint256 reserveOffset ) internal view returns (bytes32 reserveId) { // Fetch the registered reserves for this pair IKyberHintHandler kyberHint = IKyberHintHandler(_getKyberHintHandlerAddress()); (bytes32[] memory reserveIds, ,) = kyberHint.getTradingReserves( takerToken == _getWethAddress() ? KYBER_ETH_ADDRESS : takerToken, makerToken == _getWethAddress() ? KYBER_ETH_ADDRESS : makerToken, true, new bytes(0) // empty hint ); if (reserveOffset >= reserveIds.length) { return 0x0; } reserveId = reserveIds[reserveOffset]; // Ignore Kyber Bridged Reserves (0xbb) if (uint256(reserveId >> 248) == 0xbb) { return 0x0; } return reserveId; } }
Swallow failures, leaving all results as zero.
function _sampleSellForApproximateBuyFromKyber( bytes memory takerTokenData, bytes memory makerTokenData, uint256 sellAmount ) private view returns (uint256) { (address makerToken, bytes memory hint) = abi.decode(makerTokenData, (address, bytes)); (address takerToken, ) = abi.decode(takerTokenData, (address, bytes)); try this.sampleSellFromKyberNetwork (hint, takerToken, makerToken, sellAmount) returns (uint256 amount) { return amount; return 0; } }
12,801,721
./partial_match/42/0x07FDd99781852B940641A1c7DeE6440e11c6D237/sources/Implementation.sol
parameter value in dollar token/
function unbondUnderlying(uint256 value) external onlyFrozenOrFluid(msg.sender) { unfreeze(msg.sender); incrementBalanceOfStaged(msg.sender, value); decrementTotalBonded(value, "Bonding: insufficient total bonded"); decrementBalanceOf(msg.sender, balance, "Bonding: insufficient balance"); emit Unbond(msg.sender, epoch().add(1), balance, value); }
3,312,932
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0 <= 0.7.5; import "./SmartDCPABEUtility.sol"; import "./SmartDCPABEAuthority.sol"; import "./Collection.sol"; /** * @author Bruno C. P. Arruda * @title SmartDCPABE Key Management Contract * @notice This contract allow to register and find attribute public keys */ contract SmartDCPABEKeys is Collection { struct PublicKey { Bytes127 eg1g1ai; Bytes127 g1yi; } struct Bytes127 { bytes32 chunk1; bytes32 chunk2; bytes32 chunk3; bytes31 chunk4; uint8 lastChunkSize; } SmartDCPABEUtility util; SmartDCPABEAuthority authority; mapping(address => string[]) publicKeyNames; mapping(address => mapping(string => PublicKey)) ABEKeys; /** * @notice creates the contract with unset dependencies * @param root the address of the Root contract */ constructor(address root) Collection(root) {} /** * @inheritdoc Collection */ function setContractDependencies( ContractType contractType, address addr ) public override onlyOwner { if (contractType == ContractType.UTILITY) { util = SmartDCPABEUtility(addr); } else if (contractType == ContractType.AUTHORITY) { authority = SmartDCPABEAuthority(addr); } } /** * @notice register a public key of an attribute * @param addr user's address * @param name attribute name * @param eg1g1ai a component of the DCPABE attribute data structure * @param g1yi a component of the DCPABE attribute data structure */ function addPublicKey( address addr, string memory name, bytes memory eg1g1ai, bytes memory g1yi ) public { require(authority.isCertifier(addr), "certifier not found"); bytes32[3] memory eg1g1aiChunks; bytes31 eg1g1aiLastChunk; uint8 eg1g1aiLastChunkSize = uint8(eg1g1ai.length % 32); bytes32[3] memory g1yiChunks; bytes31 g1yiLastChunk; uint8 g1yiLastChunkSize = uint8(g1yi.length % 32); assembly { // writing eg1g1ai byte dynamic array on the bytes32[3] structure mstore(eg1g1aiChunks, mload(add(eg1g1ai, 0x20))) mstore(add(eg1g1aiChunks, 0x20), mload(add(eg1g1ai, 0x40))) mstore(add(eg1g1aiChunks, 0x40), mload(add(eg1g1ai, 0x60))) eg1g1aiLastChunk := mload(add(eg1g1ai, 0x80)) // writing g1yi byte dynamic array on the bytes32[3] structure mstore(g1yiChunks, mload(add(g1yi, 0x20))) mstore(add(g1yiChunks, 0x20), mload(add(g1yi, 0x40))) mstore(add(g1yiChunks, 0x40), mload(add(g1yi, 0x60))) g1yiLastChunk := mload(add(g1yi, 0x80)) } addPublicKey( addr, name, eg1g1aiChunks, eg1g1aiLastChunk, eg1g1aiLastChunkSize, g1yiChunks, g1yiLastChunk, g1yiLastChunkSize ); } /** * @notice get the public key data * @param addr user's address * @param name attribute name * @return name_ attribute name * @return eg1g1ai a component of the DCPABE attribute data structure * @return g1yi a component of the DCPABE attribute data structure */ function getPublicKey ( address addr, string memory name ) public view returns ( string memory name_, bytes memory eg1g1ai, bytes memory g1yi ) { PublicKey storage pk = ABEKeys[addr][name]; return ( name, abi.encodePacked( pk.eg1g1ai.chunk1, pk.eg1g1ai.chunk2, pk.eg1g1ai.chunk3, util.trimBytes31(pk.eg1g1ai.chunk4, pk.eg1g1ai.lastChunkSize)), abi.encodePacked( pk.g1yi.chunk1, pk.g1yi.chunk2, pk.g1yi.chunk3, util.trimBytes31(pk.g1yi.chunk4, pk.g1yi.lastChunkSize))); } /** * @notice register a public key of an attribute * @dev this function is called only by the addPublicKey public function, * after the split of the bytes values into words of 32 bytes * @param addr user's address * @param name attribute name * @param eg1g1aiChunks three first words of 32 bytes a DCPABE attribute component * named as 'eg1g1ai' * @param eg1g1aiLastChunk last bytes of 'eg1g1ai1', fit into a word of 31 bytes * @param eg1g1aiLastChunkSize the data offset inside the last word of eg1g1ai1 * @param g1yiChunks three first words of 32 bytes a DCPABE attribute component * named as 'g1yi' * @param g1yiLastChunk last bytes of 'g1yi', fit into a bytes31 variable * @param g1yiLastChunkSize the data offset inside the last word of g1yi */ function addPublicKey ( address addr, string memory name, bytes32[3] memory eg1g1aiChunks, bytes31 eg1g1aiLastChunk, uint8 eg1g1aiLastChunkSize, bytes32[3] memory g1yiChunks, bytes31 g1yiLastChunk, uint8 g1yiLastChunkSize ) internal { Bytes127 memory eg1g1ai = Bytes127( eg1g1aiChunks[0], eg1g1aiChunks[1], eg1g1aiChunks[2], eg1g1aiLastChunk, eg1g1aiLastChunkSize ); Bytes127 memory g1yi = Bytes127( g1yiChunks[0], g1yiChunks[1], g1yiChunks[2], g1yiLastChunk, g1yiLastChunkSize ); // checks existence of data to decide whether or not to push the attribute name // into the stack if (uint(ABEKeys[addr][name].eg1g1ai.chunk1) == uint(0)) { publicKeyNames[addr].push(name); authority.incrementPublicKeyCount(addr); } ABEKeys[addr][name] = PublicKey(eg1g1ai, g1yi); } }
register a public key of an attribute addr user's address name attribute name eg1g1ai a component of the DCPABE attribute data structure g1yi a component of the DCPABE attribute data structure/ writing eg1g1ai byte dynamic array on the bytes32[3] structure writing g1yi byte dynamic array on the bytes32[3] structure
function addPublicKey( address addr, string memory name, bytes memory eg1g1ai, bytes memory g1yi ) public { require(authority.isCertifier(addr), "certifier not found"); bytes32[3] memory eg1g1aiChunks; bytes31 eg1g1aiLastChunk; uint8 eg1g1aiLastChunkSize = uint8(eg1g1ai.length % 32); bytes32[3] memory g1yiChunks; bytes31 g1yiLastChunk; uint8 g1yiLastChunkSize = uint8(g1yi.length % 32); assembly { mstore(eg1g1aiChunks, mload(add(eg1g1ai, 0x20))) mstore(add(eg1g1aiChunks, 0x20), mload(add(eg1g1ai, 0x40))) mstore(add(eg1g1aiChunks, 0x40), mload(add(eg1g1ai, 0x60))) eg1g1aiLastChunk := mload(add(eg1g1ai, 0x80)) mstore(g1yiChunks, mload(add(g1yi, 0x20))) mstore(add(g1yiChunks, 0x20), mload(add(g1yi, 0x40))) mstore(add(g1yiChunks, 0x40), mload(add(g1yi, 0x60))) g1yiLastChunk := mload(add(g1yi, 0x80)) } addPublicKey( addr, name, eg1g1aiChunks, eg1g1aiLastChunk, eg1g1aiLastChunkSize, g1yiChunks, g1yiLastChunk, g1yiLastChunkSize ); }
5,461,244